How to call an appropriate method by string value from collection?

后端 未结 3 619
孤街浪徒
孤街浪徒 2021-01-28 13:06

I have a collection of strings. For example,

string[] coll={\"1\", \"2\", \"3\" ...\"100\"...\"150\"...} 

and I have respective methods for th

3条回答
  •  佛祖请我去吃肉
    2021-01-28 13:30

    Solution 1:

    Use a delegate mapping. This is the faster solution.

    private static Dictionary mapping =
        new Dictionary
        {
            { "1", MethodOne },
            // ...
            { "150", Method150 }
        };
    
    public void Invoker(string selector)
    {
        Action method;
        if (mapping.TryGetValue(selector, out method)
        {
            method.Invoke();
            return;
        }
    
        // TODO: method not found
    }
    

    Solution 2:

    Use reflection. This is slower and is appropriate only if your methods have strict naming (eg. 1=MethodOne 150=Method150 will not work).

    public void Invoker(string selector)
    {
        MethodInfo method = this.GetType().GetMethod("Method" + selector);
        if (method != null)
        {
            method.Invoke(this, null);
            return;
        }
    
        // TODO: method not found
    }
    

提交回复
热议问题