Do functors have an equivalent in C#? [duplicate]

扶醉桌前 提交于 2019-12-07 14:00:10

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!