C#委托字典添加

Xod*_*rap 4 c# delegates

我想创建一个这样的方法:

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
    }
}
Run Code Online (Sandbox Code Playgroud)

但这失败了因为它说你无法添加多播委托.有什么我想念的吗?我认为delegate关键字只是从MulticastDelegate继承的类的简写.

Mar*_*ell 8

firstList[key] = (MulticastDelegate)Delegate.Combine(firstList[key],newFunc);
Run Code Online (Sandbox Code Playgroud)

测试:

        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();
Run Code Online (Sandbox Code Playgroud)

(哪个有效)

但是,只是用来Delegate代替MulticastDelegate; 这在很大程度上是一种从未真正起作用的东西的宿醉.或更好; 特定类型的代表(也许Action).