Is it possible to store functions in a dictionary?

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

    My solution with input parameters, and a int as Key of Invoke:

      private static Dictionary MethodDictionary(string param1, string param2, int param3) => new Dictionary
        {
                {1 , () =>   Method1(param1, param2, param3) },
                {2 , () =>   Method2(param1, param2, param3) },
                {3 , () =>   Method3(param1, param2, param3) },
                {4 , () =>   Method4(param1, param2, param3) },
                {5 , () =>   Method5(param1, param2, param3) }
        };
    

    And to invoke a method:

     var methodDictionary = MethodDictionary("param1", "param2", 1);
     methodDictionary[2].Invoke();
    

    This will execute Method2.

    Hope it helps!

提交回复
热议问题