【问题标题】:how to pass any method as a parameter for another function如何将任何方法作为另一个函数的参数传递
【发布时间】:2012-01-28 03:23:18
【问题描述】:

在A班,我有

internal void AFoo(string s, Method DoOtherThing)
{
    if (something)
    {
        //do something
    }
    else
        DoOtherThing();
}

现在我需要能够将DoOtherThing 传递给AFoo()。我的要求是DoOtherThing 可以有任何返回类型几乎总是无效的签名。 B班就是这样的,

void Foo()
{
    new ClassA().AFoo("hi", BFoo);
}

void BFoo(//could be anything)
{

}

我知道我可以使用 Action 或通过实现委托(如许多其他 SO 帖子中所见)来做到这一点,但如果 B 类中的函数签名未知,如何实现??

【问题讨论】:

  • 如果函数有参数,你会如何调用它?
  • @erikH 该批次的哪个功能?
  • @nawfal ???我的意思是例如 DoSomething(int,string) 作为方法,需要一些值作为参数......
  • @erikH 是的,如果可能的话,我想像new ClassA().AFoo("hi", BFoo("", 0)); 一样传递它。希望你能得到我的要求,但我不知道解决办法..

标签: c# methods delegates parameter-passing


【解决方案1】:

您需要传递一个delegate 实例; Action 可以正常工作:

internal void AFoo(string s, Action doOtherThing)
{
    if (something)
    {
        //do something
    }
    else
        doOtherThing();
}

如果BFoo 是无参数的,它将按照您的示例中所写的那样工作:

new ClassA().AFoo("hi", BFoo);

如果它需要参数,你需要提供它们:

new ClassA().AFoo("hi", () => BFoo(123, true, "def"));

【讨论】:

  • 纯粹的光彩,一气呵成...编译后的更多评论:)
【解决方案2】:

如果您需要返回值,请使用 ActionFunc

行动: http://msdn.microsoft.com/en-us/library/system.action.aspx

功能: http://msdn.microsoft.com/en-us/library/bb534960.aspx

【讨论】:

    【解决方案3】:
    public static T Runner<T>(Func<T> funcToRun)
    {
        //Do stuff before running function as normal
        return funcToRun();
    }
    

    用法:

    var ReturnValue = Runner(() => GetUser(99));
    

    我在我的 MVC 站点上使用它来处理错误。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-20
      • 1970-01-01
      • 2019-10-09
      • 2013-04-13
      • 2019-08-19
      相关资源
      最近更新 更多