问题
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