Is it possible to store functions in a dictionary?

前端 未结 5 738
萌比男神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:18

    You can create a dictionary of string as a key and a Action as a value and use it, for sample:

    var functions = new Dictionary>();
    
    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*/ });
    

    You could use it after you deserialize your message parameter, you could use the functions dictionary:

    public void ProcessObject(MessageDTO message)
    {
        if (functions.ContainsKey(message.Name))
        {
            functions[name](message.Parameters);
        }
    }
    

提交回复
热议问题