Is it possible to store functions in a dictionary?

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

    Something similar to this:

    public class Methods
    {
        public readonly Dictionary> MethodsDict = new Dictionary>();
    
        public Methods()
        {
            MethodsDict.Add("Method1", Method1);
            MethodsDict.Add("Method2", Method2);
        }
    
        public string Execute(string methodName, string[] strs)
        {
            Func method;
    
            if (!MethodsDict.TryGetValue(methodName, out method))
            {
                // Not found;
                throw new Exception();
            }
    
            object result = method(strs);
    
            // Here you should serialize result with your JSON serializer
            string json = result.ToString();
    
            return json;
        }
    
        public object Method1(string[] strs)
        {
            return strs.Length;
        }
    
        public object Method2(string[] strs)
        {
            return string.Concat(strs);
        }
    }
    

    Note that you could make it all static, if the methods don't need to access data from somewhere else.

    The return type I chose for the delegates is object. In this way the Execute method can serialize it to Json freely.

提交回复
热议问题