代码之家  ›  专栏  ›  技术社区  ›  Xodarap

C#代表字典添加

  •  4
  • Xodarap  · 技术社区  · 15 年前

    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
        }
    }
    

    1 回复  |  直到 15 年前
        1
  •  8
  •   Marc Gravell    15 年前
    firstList[key] = (MulticastDelegate)Delegate.Combine(firstList[key],newFunc);
    

    带测试:

            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();
    

    但是tbh,就用这个 Delegate MulticastDelegate ; 这在很大程度上是一些从未真正起作用的东西的后遗症。或更好;特定的 类型 Action ).