如何将任何方法作为另一个函数的参数传递

在Aclass,我有

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或实现代表来实现这一点(如许多其他SOpost中所见)但如果B类函数的签名未知,怎么能实现呢?

您需要传递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")); 

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

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

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

 public static T Runner(Func funcToRun) { //Do stuff before running function as normal return funcToRun(); } 

用法:

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

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