将一个方法作为参数传递

7

如何将方法作为参数传递? 我在Javascript中经常这样做,并需要使用匿名方法来传递参数。 在C#中该怎么做?

protected void MyMethod(){
    RunMethod(ParamMethod("World"));
}

protected void RunMethod(ArgMethod){
    MessageBox.Show(ArgMethod());
}

protected String ParamMethod(String sWho){
    return "Hello " + sWho;
}
5个回答

13

委托提供这种机制。在C# 3.0中,为您的示例快速实现此操作的方法是使用Func<TResult>,其中TResultstring和lambda表达式。

然后,您的代码将变成:

protected void MyMethod(){
    RunMethod(() => ParamMethod("World"));
}

protected void RunMethod(Func<string> 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;
}

这段代码无法编译。RunMethod需要一个Func<TResult>参数,而你传递给它的是Func<TArg,TResult>。 - Stan R.

9

您的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;
}

谢谢你的回答。我遇到了一个编译错误:“...RunMethod(Func<String,String>,String)有一些无效的参数。” - Praesagus
1
你使用的是哪个版本的C#? - Mark Rushakoff

7

非常好的链接,谢谢。这是其中之一:http://www.mujahiddev.com/2009/01/lambda-expressions-c.html - Praesagus

4
protected String ParamMethod(String sWho)
{
    return "Hello " + sWho;
}

protected void RunMethod(Func<string> ArgMethod)
{
    MessageBox.Show(ArgMethod());
}

protected void MyMethod()
{
    RunMethod( () => ParamMethod("World"));
}

那个 () => 很重要。它从 ParamMethod 中创建了一个匿名的 Func<string>

0
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;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接