是否可以将功能存储在字典中? [英] Is it possible to store functions in a dictionary?
问题描述
我有一条消息进入我的C#应用程序,这是一个序列化为JSON的对象,当我反序列化它时,我有一个名称" string
和一个有效负载" string []
,我希望能够使用名称"并使用有效载荷"数组作为其参数在函数字典中查找它,然后将输出返回给发送消息的客户端,这在C#中可能吗?
I have a message coming into my C# app which is an object serialized as JSON, when i de-serialize it I have a "Name" string
and a "Payload" string[]
, I want to be able to take the "Name" and look it up in a function dictionary, using the "Payload" array as its parameters and then take the output to return to the client sending the message, is this possible in C#?
我在此处找到了堆栈溢出的答案,其中第二部分似乎是合理的,但我不知道我在说什么'm用 State
I've found a stack overflow answer here where the second part seems plausible but i don't know what I'm referencing with State
推荐答案
听起来您可能想要这样的东西:
It sounds like you probably want something like:
Dictionary<string, Func<string[], int>> functions = ...;
这是假设函数返回一个 int
(您尚未指定).因此,您可以这样称呼它:
This is assuming the function returns an int
(you haven't specified). So you'd call it like this:
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
}
尚不清楚您要从何处填充 functions
的位置,但是如果它是同一类中的方法,则可能会有类似的内容:
It's not clear where you're trying to populate functions
from, but if it's methods in the same class, you could have something like:
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
这篇关于是否可以将功能存储在字典中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!