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

Tro*_*i94 35 c# dictionary

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

我在这里找到了堆栈溢出答案,其中第二部分看似合理,但我不知道我所引用的是什么State

Jon*_*eet 49

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

Dictionary<string, Func<string[], int>> functions = ...;
Run Code Online (Sandbox Code Playgroud)

这假设函数返回一个int(你还没有指定).所以你会这样称呼它:

int result = functions[name](parameters);
Run Code Online (Sandbox Code Playgroud)

或者验证名称:

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

目前还不清楚你functions要从哪里填充,但如果它是同一个类中的方法,你可以有类似的东西:

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
Run Code Online (Sandbox Code Playgroud)


Fel*_*ani 5

您可以创建一个string作为键的字典和Action<string[]>作为值的字典并使用它,用于示例:

var functions = new Dictionary<string, Action<string[]>>();

functions.Add("compute", (p) => { /* use p to compute something*/ });
functions.Add("load", (p) => { /* use p to compute something*/ });
functions.Add("process", (p) => { /* use p to process something*/ });
Run Code Online (Sandbox Code Playgroud)

您可以在反序列化消息参数后使用它,您可以使用functions字典:

public void ProcessObject(MessageDTO message)
{
    if (functions.ContainsKey(message.Name))
    {
        functions[name](message.Parameters);
    }
}
Run Code Online (Sandbox Code Playgroud)