我有一个MulticastDelegate,它可以引用具有相同签名的许多(传统)委托之一。例如:

public delegate void ObjectCreated(object sender, EventArgs args);
public delegate void ObjectDeleted(object sender, EventArgs args);
//...


然后使用这些委托来定义事件:

public event ObjectCreated ObjectWasCreated;
public event ObjectDeleted ObjectWasDeleted;


然后,我有一个采用MulticastDelegate的方法,该方法用于进行一些常见的检查:

void DispatchEvent(MulticastDelegate handler, object sender, EventArgs args)
{
    if (handler != null)
    {
        // ...
        handler.DynamicInvoke(sender, args);
    }
}


从定义事件的类的其他方法中调用:

DispatchEvent(ObjectWasCreated, sender, args);
DispatchEvent(ObjectWasDeleted, sender, args);


有没有更简洁的方法可以避免DynamicInvoke?

最佳答案

这是我的无反射解决方案。它基本上将多播委托实现为列表。更少的代码?不,性能更好吗?我不知道。清洁器?嗯

public delegate void ObjectCreated(object sender, EventArgs args);
public delegate void ObjectDeleted(object sender, EventArgs args);

public event ObjectCreated ObjectWasCreated
{
    add
    {
        m_ObjectCreatedSubscribers.Add(value.Invoke);
    }
    remove
    {
        m_ObjectCreatedSubscribers.RemoveAll(e => e.Target.Equals(value));
    }
}
public event ObjectDeleted ObjectWasDeleted
{
    add
    {
        m_ObjectDeletedSubscribers.Add(value.Invoke);
    }
    remove
    {
        m_ObjectDeletedSubscribers.RemoveAll(e => e.Target.Equals(value));
    }
}

private List<Action<object, EventArgs>> m_ObjectCreatedSubscribers = new List<Action<object, EventArgs>>();
private List<Action<object, EventArgs>> m_ObjectDeletedSubscribers = new List<Action<object, EventArgs>>();

void DispatchEvent(List<Action<object, EventArgs>> subscribers, object sender, EventArgs args)
{
    foreach (var subscriber in subscribers)
        subscriber(sender, args);
}

关于c# - 在避免DynamicInvoke的同时使用MulticastDelegate作为参数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/4751799/

10-13 08:33