我正在看这里发布的例子:从字典中调用方法,是否有人可以提出更真实的东西?
调用一个具有更多复杂参数的方法,我试着在这里调整示例,但很抱歉,没有足够的经验.
这是发布但是如何调用这样的方法?
private static void Method1(string[] curr, string[] prev, int counter)
{
var a1 = curr[5];
Console.WriteLine(a1);
}
Run Code Online (Sandbox Code Playgroud)
对不起,如果问题有点"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);
}
Run Code Online (Sandbox Code Playgroud)
如果我正确理解了你的问题...你可以Method1在字典中调用,就像在你的例子中一样:
var methods = new Dictionary<int, Action<string[], string[], int>>();
methods.Add(1, Method1);
methods[1](new[]{"Hello"}, new[]{"World"}, 1);
Run Code Online (Sandbox Code Playgroud)
您只需使用Action的另一个重载创建字典
更新:
如果你Method1看起来像:
static int Method1(string[] curr, string[] prev, int counter)
{
return 4;
}
Run Code Online (Sandbox Code Playgroud)
然后你应该使用Func委托:
var methods = new Dictionary<int, Func<string[], string[], int, int>>();
methods.Add(1, Method1);
var result = methods[1](new[]{"Hello"}, new[]{"World"}, 1);
Run Code Online (Sandbox Code Playgroud)