Storing methods in a dictionary and using these methods when keys match.

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

      

Is it possible to store this method in a dictionary and call this method if Dicitionary contains the method key value.

For example, for example:

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

string input = "hello"

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

      

+3


source to share


3 answers


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");
    }
}

      



+5


source


Yes, it's pretty easy: just use the class Action

:

Encapsulates a method that takes no parameters and does not return a value.



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

dict.Add("hello", test);

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

      

Demo

+3


source


You can use Func to reference your methods and then call them in a loop https://msdn.microsoft.com/en-us/library/bb549151%28v=vs.110%29.aspx?f=255&MSPPError=-2147217396

And as @Lucas Trzesniewski answered that you can use Action

if your methods have no parameters

0


source







All Articles