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

4
例如,我想要调用的主方法是这个:
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调用。我无法更改它的参数。我在此犯了一个笔误。


2
注意:您有一个返回字符串的空方法-这将无法编译。我的答案会改变它。 - Reed Copsey
5个回答

21

您可以通过在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";
    }
 });

当然,这只有在2是一个变量而不是字面值时才有意义。 :-) - Steven Sudit
当然,只需要将代码与问题匹配即可。[原文:MasterMethod(StringSelection(2));] - Reed Copsey

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

@Steven 我想编辑,但我认为答案已经在其他地方得到了很好的解决。 - dove

2

1

我认为你正在寻找一个委托


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