c# - 是否可以将函数存储在字典中?

标签 c# dictionary

我有一条消息进入我的 C# 应用程序,它是一个序列化为 JSON 的对象,当我反序列化它时,我有一个“名称”string 和一个“Payload”string[ ],我希望能够获取“Name”并在函数字典中查找它,使用“Payload”数组作为其参数,然后获取输出以返回给发送消息的客户端,是这在 C# 中可能吗?

我找到了一个堆栈溢出答案 here第二部分似乎是合理的,但我不知道我在用 State

引用什么

最佳答案

听起来您可能想要这样的东西:

Dictionary<string, Func<string[], int>> functions = ...;

这是假设函数返回一个 int(您没有指定)。所以你会这样调用它:

int result = functions[name](parameters);

或者验证名称:

Func<string[], int> function;
if (functions.TryGetValue(name, out function))
{
    int result = function(parameters);
    ...
}
else
{
    // No function with that name
}

不清楚您要从哪里填充函数,但如果它是同一个类中的方法,您可能有类似的东西:

Dictionary<string, Func<string[], int>> functions = 
    new Dictionary<string, Func<string[], int>>
{
    { "Foo", CountParameters },
    { "Bar", SomeOtherMethodName }
};

...

private static int CountParameters(string[] parameters)
{
    return parameters.Length;
}

// etc

关于c# - 是否可以将函数存储在字典中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30397846/

相关文章:

c# - 在 Web 和桌面应用程序中同步数据库?

c# - ConcurrentDictionary 多次添加相同的键

python - 为什么循环中的 dict.pop() 会从 future 循环迭代中创建的字典中删除键?

pandas - 如果数据框列值匹配字典键,检查不同的列是否匹配字典值

c# - 任务管理器图标选项

c# - Adobe Sign(echo sign) API 发送文档使用C#

C# - 当其他属性被修改时自动更新对象属性

c# - 白鲸记的异常(exception)

python - 如何在 python 中更改字典中的列表值?

python - 计算列表中的项目并使其成为字典