是否可以在C#中将方法声明为参数?

时间:2009-09-22 16:44:35

标签: c#

例如我要调用的主要方法是:

public static void MasterMethod(string Input){
    /*Do some big operation*/
}
通常,我会做这样的事情:

public static void StringSelection(int a)
{
    if(a == 1)
    {
       return "if";
    }
    else
    {
       return "else";
    }
}

MasterMethod(StringSelection(2));

但我想做这样的事情:

MasterMethod( a = 2
     {
        if(a == 1)
        {
           return "if";
        }
        else
        {
           return "else";
        }
     });

其中2以某种方式作为输入传递给操作。

这可能吗?这有名字吗?

编辑::请注意,MasterMethod是一个API调用。我无法更改它的参数。我不小心弄错了。

5 个答案:

答案 0 :(得分:20)

您可以通过delegates in C#

执行此操作
public static string MasterMethod(int param, Func<int,string> function)
{
    return function(param);
}


// Call via:
string result = MasterMethod(2, a => 
{
    if(a == 1)
    {
       return "if";
    }
    else
    {
       return "else";
    }
 });

答案 1 :(得分:3)

您可以使用匿名代表执行此操作:

    delegate string CreateString();

    public static void MasterMethod(CreateString fn)
    {
        string something = fn();
        /*Do some big operation*/
    }

    public static void StringSelection(int a)
    {
        if(a == 1)
        {
           return "if";
        }
        else
        {
           return "else";
        }
    }

    MasterMethod(delegate() { return StringSelection(2); });

答案 2 :(得分:2)

答案 3 :(得分:2)

是的,请使用delegate。其中包括Lambda Expressionsanonymous methods

答案 4 :(得分:1)

我认为您正在寻找delegate

相关问题