How to use a collection to store a delegate?

I wanted to have a hash table with a row as a key and a pointer function (delegate) as a value. This method invokes the correct procedure specified by the row-based command. However, the compiler will not eat it.

What am I doing wrong?

//declaration
     public delegate void categoryHandler(String request);     

//init code
     Hashtable categories = new Hashtable();
     categories.Add("campaigns", Campaigns.post);

//function call
     String category = "campaigns";
     categoryHandler handler = (categoryHandler) categories[category];
     if (handler != null)
     {
          handler(someString);
     }

//handler
     static public void post(String request)
     {
          ...
     }

The error I get is on the line where I put this function in the hash table: Error 2 Argument "2": cannot be converted from a "method group" to an "object"

I hope this is just some kind of semantic thing that I forgot ... But if this cannot be done ... is there any other way to have some kind of Stum-based jumptable?

+3
source share
4 answers

, Hashtable, . ( , ), , .

Hashtable, :

categoryHandler handler = Campaigns.post;
categories.Add("campaigns", handler);

categories.Add("campaigns", new categoryHandler(Campaigns.post));

, .

Dictionary<string, categoryHandler> - , ( ). CategoryHandler btw - . post post.

, , :

 String category = "campaigns";
 CategoryHandler handler;
 if (categories.TryGetValue(category, out handler))
 {
     handler(someString);
 }
+8

.Net 3.5, , , switch:

private readonly Dictionary<string, Action<string>> _lookupTable = new Dictionary<string, Action<string>>
{
    {"campaigns", post}
    {"somethingElse", doSomethingElse}
    {"tryIt", val => doSomethingWithVal(val)} 
};

, switch, :

_lookupTable["foo"]("bar");
+2

-

.

//declaration
     public delegate void categoryHandler(String request);     

//init code
     Dictionary<string, categoryHandler> categories = new Dictionary<string, categoryHandler> ;
     categories.Add("campaigns", Campaigns.post);

//function call
     string category = "campaigns";

     if (!categories.ContainsKey(category))
     {
        // Key not there just return
        return;
     }

     categoryHandler handler = categories[category];  // NO need to cast here

     if (handler != null)
     {
          handler(someString);
     }

//handler
     static public void post(String request)
     {
          ...
     }
+1
source

Depending on the version of C # you are using, you may need to:

categories.Add("campaigns", new categoryHandler(Campaigns.post));

Aside, if you are using .NET 2.0 or higher, you should use a generic Dictionary<T,T>class instead Hashtable.

0
source

Source: https://habr.com/ru/post/1717931/


All Articles