如何将方法作为参数传递?我一直在Javascript中这样做,需要使用匿名方法来传递params.我怎么在c#中做到这一点?
protected void MyMethod(){
RunMethod(ParamMethod("World"));
}
protected void RunMethod(ArgMethod){
MessageBox.Show(ArgMethod());
}
protected String ParamMethod(String sWho){
return "Hello " + sWho;
}
Run Code Online (Sandbox Code Playgroud)
Jef*_*tes 13
代表们提供这种机制.一个快速的方法来为你的例子做这在C#3.0是使用Func<TResult>地方TResult是string和lambda表达式.
您的代码将变为:
protected void MyMethod(){
RunMethod(() => ParamMethod("World"));
}
protected void RunMethod(Func<string> method){
MessageBox.Show(method());
}
protected String ParamMethod(String sWho){
return "Hello " + sWho;
}
Run Code Online (Sandbox Code Playgroud)
但是,如果您使用的是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;
}
Run Code Online (Sandbox Code Playgroud)
您的ParamMethod类型为Func <String,String>,因为它接受一个字符串参数并返回一个字符串(请注意,有角度括号中的最后一项是返回类型).
所以在这种情况下,你的代码会变成这样:
protected void MyMethod(){
RunMethod(ParamMethod, "World");
}
protected void RunMethod(Func<String,String> ArgMethod, String s){
MessageBox.Show(ArgMethod(s));
}
protected String ParamMethod(String sWho){
return "Hello " + sWho;
}
Run Code Online (Sandbox Code Playgroud)