c# - 如何在 C# 中为不同的类传递函数指针委托(delegate)

标签 c# c++ delegates function-pointers

在 C++ 中, 对于接受具有 void 返回类型的函数指针的函数,例如:

void TakesFun(Func<void ()>  fun ){
    fun();
}

以上函数可以通过这些方式调用

//if foo is a function returning void but is declared in global space and not part of another class
TakesFun(bind(foo));   
//if foo is a function returning void but is declared in class called ClassX and the function is required to be called for object "obj".
TakesFun(bind(ClassX::foo, obj));   
//if foo is a function taking an integer as argument and returning void but is declared in class called ClassX and the function is required to be called for object "obj".
TakesFun(bind(ClassX::foo, obj, 5)); //5 is the argument supplied to function foo   

你能帮我为 3 个类似的函数调用编写 C# 代码吗?我尝试阅读有关委托(delegate)的内容,但示例并未涵盖上述所有 3 种情况。

最佳答案

正如@Backs 所说,您可以像这样定义TakesFun 函数:

void TakesFun(Action action) => action();

如果需要传递参数,可以这样用:

void TakesFun<TParam>(Action<TParam> action, TParam p) => action(p);

您的 3 个示例将是:

TakesFun(SomeClass.Foo); // 'Foo' is a static function of 'SomeClass' class
TakesFun(obj.Foo); // 'Foo' is a function of some class and obj is instance of this class
TakesFun(obj.Foo, "parameter"); // as above, but will pass string as parameter to 'Foo'

关于c# - 如何在 C# 中为不同的类传递函数指针委托(delegate),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50902705/

相关文章:

c# - 指针的黑魔法

c# - 使用 C# MongoDB 将 Int 转换为 String?

c++ - Eigen:使用 Eigen intrinsics 简化表达式

c++ - flush 属性在 SimpleFileChannel 中的工作原理

c# - 在字典中存储委托(delegate)

iphone - AppDelegate 中的 didSelectViewController 没有被调用

c# - 可以在 Finally block 的中间引发 ThreadAbortException 吗?

c# - 用于通用方法的 Microsoft Fakes shim

c++ - 将 QString 转换为 float 给我错误

ios - 应用程序委托(delegate)中的方法