本文介绍了如何在C#中为其他类传递函数指针委托的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在c ++中,
到一个函数中,该函数接受一个带有无效返回类型的函数指针,例如:
In c++,To a function that takes in a function pointer with void return type, eg:
void TakesFun(Func<void ()> fun ){
fun();
}
上述功能可以通过以下方式调用
Above function can be called in these ways
//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#代码吗电话吗?我尝试阅读有关Delegates的内容,但示例并未涵盖上述所有3种情况。
Could you help me write C# code for 3 similar function calls? I tried reading up on Delegates, but the examples do not cover all the above 3 cases.
推荐答案
正如@Backs所说,您可以这样定义 TakesFun
函数:
As @Backs said, you can define TakesFun
function like this:
void TakesFun(Action action) => action();
如果需要传递参数,则可以使用以下命令:
If you need to pass a parameter, you can use this:
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#中为其他类传递函数指针委托的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!