【问题标题】:How do I pass a function pointer delegate for a different class in c#如何在 c# 中为不同的类传递函数指针委托
【发布时间】:2018-11-26 21:36:43
【问题描述】:

在 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# 代码吗?我尝试阅读 Delegates,但示例并未涵盖上述所有 3 种情况。

【问题讨论】:

    标签: c# c++ delegates function-pointers


    【解决方案1】:

    正如@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'
    

    【讨论】:

    • 我可以让 TakesFun 的语法能够为操作采用任意数量的参数吗?
    • 当然,有一点小技巧,见this SO question
    【解决方案2】:

    您可以随时传递Action

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

    【讨论】:

      猜你喜欢
      • 2012-01-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-02
      • 2010-09-28
      • 2022-08-24
      • 1970-01-01
      相关资源
      最近更新 更多