C# delegate dictionary add
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 you can't add multicast delegates. I开发者_JS百科s there something I'm missing? I thought the delegate keyword was just shorthand for a class which inherits from MulticastDelegate.
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 works)
But tbh, Just use Delegate
in place of MulticastDelegate
; this is largely a hangover from something that never really worked. Or better; a specific type of delegate (perhaps Action
).
精彩评论