本文介绍了使用MulticastDelegate为参数,同时避免DynamicInvoke的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 MulticastDelegate 可以引用一些具有相同签名(传统)的代表之一。例如:

I have a MulticastDelegate that can reference one of a number of (legacy) delegates that have the same signature. For example:

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



这些代表随后被用来定义事件:

Those delegates are then used to define events:

public event ObjectCreated ObjectWasCreated;
public event ObjectDeleted ObjectWasDeleted;



然后我有这需要在 MulticastDelegate ,我用它来执行一些常规检查:

I then have a method which takes in a MulticastDelegate that I use to do some common checking:

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



其中是从类,其中的其它方法中调用该事件被定义为:

Which is called from within other methods of the class wherein the events were defined:

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



有没有做到这一点更简洁的方式,避免DynamicInvoke?

Is there a more concise way to do this that avoids DynamicInvoke?

推荐答案

下面是我的无反射的解决方案。它基本上实现了多播委托为列表。更少的代码?第更好的性能?我不知道。清洁器? 。MEH

Here's my reflection-free solution. It basically implements a multicast delegate as a list. Less code? No. Better performance? I don't know. Cleaner? Meh.

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

这篇关于使用MulticastDelegate为参数,同时避免DynamicInvoke的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-20 09:51