Is it possible to store functions in a dictionary?

前端 未结 5 736
萌比男神i
萌比男神i 2021-02-01 14:46

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[]

5条回答
  •  北恋
    北恋 (楼主)
    2021-02-01 15:20

    It sounds like you probably want something like:

    Dictionary> functions = ...;
    

    This is assuming the function returns an int (you haven't specified). So you'd call it like this:

    int result = functions[name](parameters);
    

    Or to validate the name:

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

    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> functions = 
        new Dictionary>
    {
        { "Foo", CountParameters },
        { "Bar", SomeOtherMethodName }
    };
    
    ...
    
    private static int CountParameters(string[] parameters)
    {
        return parameters.Length;
    }
    
    // etc
    

提交回复
热议问题