在字典中保存方法并在键匹配时使用这些方法。

时间:2015-05-09 21:44:45

标签: c#

Public void test(){
   Console.WriteLine("Hello World");
}

是否可以在Dictionary中保存此方法,如果Dicitionary包含方法的键值,则调用此方法。

例如:

Hashtable table = new Hashtable<method, string>();

string input = "hello"

foreach(Dictionary.entry t in table){
    if(input == t.Key){
        //Call the t.value method.
     }
}

2 个答案:

答案 0 :(得分:5)

class Program
{
    private static void Main(string[] args)
    {
        var methods = new Dictionary<string, Action>();
        //choose your poison:
        methods["M1"] = MethodOne; //method reference
        methods["M2"] = () => Console.WriteLine("Two"); //lambda expression
        methods["M3"] = delegate { Console.WriteLine("Three"); }; //anonymous method
        //call `em
        foreach (var method in methods)
        {
            method.Value();
        }
        //or like tis
        methods["M1"]();
    }

    static void MethodOne()
    {
        Console.WriteLine("One");
    }
}

答案 1 :(得分:3)

是的,这很简单:只需使用Action委托类:

  

封装没有参数且不返回值的方法。

var dict = new Dictionary<string, Action>();

dict.Add("hello", test);

var input = "hello";
dict[input]();

Demo