Added C # delegate dictionary

I want to create a method like this:

private static void AddOrAppend<K>(this Dictionary<K, MulticastDelegate> firstList, K key, MulticastDelegate newFunc) { if (!firstList.ContainsKey(key)) { firstList.Add(key, newFunc); } else { firstList[key] += newFunc; // this line fails } } 

But this fails because it says that you cannot add multicast delegates. Is there something I'm missing? I thought the delegate keyword was simply abbreviated for a class that inherits from MulticastDelegate.

+4
source share
1 answer
 firstList[key] = (MulticastDelegate)Delegate.Combine(firstList[key],newFunc); 

with test:

  var data = new Dictionary<int, MulticastDelegate>(); Action action1 = () => Console.WriteLine("abc"); Action action2 = () => Console.WriteLine("def"); data.AddOrAppend(1, action1); data.AddOrAppend(1, action2); data[1].DynamicInvoke(); 

(which is working)

But tbh, just use Delegate instead of MulticastDelegate ; it's pretty much a hangover from something that never worked. Or better; a specific type of delegate (possibly Action ).

+8
source

All Articles