我希望能够将方法作为参数传递.
例如..
//really dodgy code
public void PassMeAMethod(string text, Method method)
{
  DoSomething(text);
  // call the method
  //method1();
  Foo();
}
public void methodA()
{
  //Do stuff
}
public void methodB()
{
  //Do stuff
}
public void Test()
{
  PassMeAMethod("calling methodA", methodA)
  PassMeAMethod("calling methodB", methodB)
}
我怎样才能做到这一点?
Ste*_*eld 21
您需要使用委托,这是一个表示方法的特殊类.您可以定义自己的委托或使用其中一个内置委托,但委托的签名必须与您要传递的方法匹配.
定义你自己的:
public delegate int MyDelegate(Object a);
此示例匹配返回整数并将对象引用作为参数的方法.
在您的示例中,methodA和methodB都没有参数返回void,因此我们可以使用内置的Action委托类.
以下是您修改的示例:
public void PassMeAMethod(string text, Action method)
{
  DoSomething(text);
  // call the method
  method();    
}
public void methodA()
{
//Do stuff
}
public void methodB()
{
//Do stuff
}
public void Test()
{
//Explicit
PassMeAMethod("calling methodA", new Action(methodA));
//Implicit
PassMeAMethod("calling methodB", methodB);
}
如您所见,您可以显式或隐式地使用委托类型,以适合您的方式.
使用 Action<T>
例:
public void CallThis(Action x)
{
    x();
}
CallThis(() => { /* code */ });
或者Func <>
Func<int, string> func1 = (x) => string.Format("string = {0}", x);
PassMeAMethod("text", func1);
public void PassMeAMethod(string text, Func<int, string> func1)
{
  Console.WriteLine( func1.Invoke(5) );
}