小编Chr*_*ley的帖子

+ =和Delegate.Combine之间的区别

我建立了一个事件系统,该事件系统维护一个dictionary委托,dictionary通过通用的Subscribe / Unsubscribe方法(每个方法都采用Action typeT)向其中添加/删除元素,并具有一个Publish方法,以在发生某些情况时通知订阅者。采取类型为T的动作)。一切正常,但是我注意到在向元素添加或删除元素时不能使用+ =或-= dictionary,因为传递给方法的类型(T的动作)与dictionaryDelegate)中存储的类型不匹配。以下代码段显示了我可以做什么和不能做什么。

private readonly Dictionary<Type, Delegate> delegates = new Dictionary<Type, Delegate>();

public void Subscribe<T>(Action<T> del)
{
    if (delegates.ContainsKey(typeof(T)))
    {
        // This doesn't work!
        delegates[typeof(T)] += del as Delegate;
        // This doesn't work!
        delegates[typeof(T)] += del;
        // This is ok
        delegates[typeof(T)] = (Action<T>)delegates[typeof(T)] + del;
        // This is ok
        var newDel = (Action<T>)delegates[typeof(T)] + del;
        delegates[typeof(T)] = newDel;
        // This is ok
        del += (Action<T>)delegates[typeof(T)];
        delegates[typeof(T)] = …
Run Code Online (Sandbox Code Playgroud)

c# delegates

5
推荐指数
1
解决办法
147
查看次数

标签 统计

c# ×1

delegates ×1