如何在 C# 中为不同的 class 传递函数指针委托
How do I pass a function pointer delegate for a different class in c#
在 C++ 中,
到一个接受 void return 类型的函数指针的函数,例如:
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# 代码吗?我尝试阅读有关代表的内容,但示例并未涵盖上述所有 3 种情况。
你总是可以传递 Action
:
void TakesFun(Action action)
{
action();
}
///...
TestFun(() => SomeMethod(1,2,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++ 中, 到一个接受 void return 类型的函数指针的函数,例如:
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# 代码吗?我尝试阅读有关代表的内容,但示例并未涵盖上述所有 3 种情况。
你总是可以传递 Action
:
void TakesFun(Action action)
{
action();
}
///...
TestFun(() => SomeMethod(1,2,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'