传递方法作为参数

如何将方法作为参数传递? 我一直在Javascript中这样做,需要使用匿名方法来传递params。 我怎么在c#中做到这一点?

protected void MyMethod(){ RunMethod(ParamMethod("World")); } protected void RunMethod(ArgMethod){ MessageBox.Show(ArgMethod()); } protected String ParamMethod(String sWho){ return "Hello " + sWho; } 

代表们提供这种机制。 在C#3.0中为您的示例执行此操作的快速方法是使用Func ,其中TResultstring和lambdas。

您的代码将变为:

 protected void MyMethod(){ RunMethod(() => ParamMethod("World")); } protected void RunMethod(Func method){ MessageBox.Show(method()); } protected String ParamMethod(String sWho){ return "Hello " + sWho; } 

但是,如果您使用的是C#2.0,则可以使用匿名委托:

 // Declare a delegate for the method we're passing. delegate string MyDelegateType(); protected void MyMethod(){ RunMethod(delegate { return ParamMethod("World"); }); } protected void RunMethod(MyDelegateType method){ MessageBox.Show(method()); } protected String ParamMethod(String sWho){ return "Hello " + sWho; } 

您的ParamMethod类型为Func ,因为它接受一个字符串参数并返回一个字符串(请注意,有角度括号中的最后一项是返回类型)。

所以在这种情况下,你的代码会变成这样:

 protected void MyMethod(){ RunMethod(ParamMethod, "World"); } protected void RunMethod(Func ArgMethod, String s){ MessageBox.Show(ArgMethod(s)); } protected String ParamMethod(String sWho){ return "Hello " + sWho; } 

看看C#代表

http://msdn.microsoft.com/en-us/library/ms173171(VS.80).aspx

教程http://www.switchonthecode.com/tutorials/csharp-tutorial-the-built-in-generic-delegate-declarations

 protected String ParamMethod(String sWho) { return "Hello " + sWho; } protected void RunMethod(Func ArgMethod) { MessageBox.Show(ArgMethod()); } protected void MyMethod() { RunMethod( () => ParamMethod("World")); } 

() =>很重要。 它从Func创建一个匿名的Func Func ,即ParamMethod。

 protected delegate String MyDelegate(String str); protected void MyMethod() { MyDelegate del1 = new MyDelegate(ParamMethod); RunMethod(del1, "World"); } protected void RunMethod(MyDelegate mydelegate, String s) { MessageBox.Show(mydelegate(s) ); } protected String ParamMethod(String sWho) { return "Hello " + sWho; }