c# - 调用存储在字典中的方法

标签 c# dictionary

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

调用的方法有一些比较复杂的参数,我试着调整了这里的例子,但是很抱歉,经验不够。

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

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/

相关文章:

c# - 为什么枚举数组不能用于参数 Enum[]?

python - python中如果value是key则删除字典的value

java - 为什么 Hashtable 不是 Java Collection 框架的一部分?

javascript - 将字典转换为保留字典键的数组

c# - 克隆列表<T>

C# 慢速绘制事件 : painting large number of objects

c# - 程序在启动后几乎立即崩溃

C#日期时间格式转换

Python SQL 对象按字典和日期选择数据

vba - 自动过滤器可以从字典键中获取包含和非包含通配符吗?