How do I pass a function pointer delegate for a different class in c#

半城伤御伤魂 提交于 2019-12-11 08:54:04

问题


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   

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.


回答1:


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);

Your 3 examples will be:

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'



回答2:


You can always pass an Action:

void TakesFun(Action action)
{
    action();
}
///...
TestFun(() => SomeMethod(1,2,3));


来源:https://stackoverflow.com/questions/50902705/how-do-i-pass-a-function-pointer-delegate-for-a-different-class-in-c-sharp

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