在 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/