gpt4 book ai didi

c# - 使用 MulticastDelegate 作为参数同时避免 DynamicInvoke

转载 作者:行者123 更新时间:2023-11-30 16:31:39 27 4
gpt4 key购买 nike

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

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

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

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?

最佳答案

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

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# - 使用 MulticastDelegate 作为参数同时避免 DynamicInvoke,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4751799/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com