我正在查看此处发布的示例:用于从字典中调用方法, 谁能提出一些更真实的世界?
调用的方法有一些比较复杂的参数,我试着调整了这里的例子,但是很抱歉,经验不够。
这已发布,但如何调用这样的方法?
private static void Method1(string[] curr, string[] prev, int counter)
{
var a1 = curr[5];
Console.WriteLine(a1);
}
抱歉,如果问题有点“小马托尼”:-)
上一个发布示例如下
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);
关于c# - 调用存储在字典中的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28320063/