调用存储在字典中的方法

Call methods stored in a dictionary

我正在查看此处发布的示例:用于从字典中调用方法, 谁能推荐一些更真实的世界?

调用一个方法,参数比较多,参数比较复杂,试过调整这里的例子,不好意思,经验不够

已发布,但如何调用这样的方法?

private static void Method1(string[] curr, string[] prev, int counter)
{
    var a1 = curr[5];
    Console.WriteLine(a1);
}

对不起,如果问题有点"tony the pony" :-)

上一个发布示例如下

    private static void Method1(int x)
    {
        Console.WriteLine(x);
    }

    private static void Method2(int x)
    {
    }

    private static void Method3(int x)
    {
    }

    static void Main(string[] args)
    {
        Dictionary<int, Action<int>> methods = new Dictionary<int, Action<int>>();
        methods.Add(1, Method1);
        methods.Add(2,  Method2);
        methods.Add(3, Method3);

        (methods[1])(1);
    }

如果我正确理解你的问题... 您也可以从字典中调用 Method1,就像在您的示例中一样:

var methods = new Dictionary<int, Action<string[], string[], int>>();
methods.Add(1, Method1);

methods[1](new[]{"Hello"}, new[]{"World"}, 1);

您只需使用 Action

的另一个重载创建字典

更新:

如果您的 Method1 看起来像:

static int Method1(string[] curr, string[] prev, int counter)
{
    return 4;
}

那么你应该使用Func委托:

var methods = new Dictionary<int, Func<string[], string[], int, int>>();
methods.Add(1, Method1);

var result = methods[1](new[]{"Hello"}, new[]{"World"}, 1);