我有一条消息进入我的 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/