问题
Is there an equivalent to Functors in C#?
C# has Func<,>, delegates and anonymous methods but aren't all of these pointers to a method?
The C++ Functor is a class and not a pointer to a method.
回答1:
C# has Func<,>, delegates and anonymous methods but aren't all of these pointers to a method?
No. Even C# delegates are classes, implemented by the compiler for you. These generated classes (for delegates) are derived from MulticastDelegate which in turn derives from Delegate.
In short, a delegate is a syntactic sugar for a class generated by compiler.
回答2:
Both lambdas (Func<>
, Action<>
) and delegates (named as well as anonymous) are classes.
If you need a pointer to method (to pass it into unsafe code, for instance) you should use marshalling:
IntPtr pFunc = Marshal.GetFunctionPointerForDelegate(myDelegate);
来源:https://stackoverflow.com/questions/17136025/do-functors-have-an-equivalent-in-c