副标题:EventHandlerList 键的类型可以不是对象吗?
我想使用枚举存储我想在 EventHandler 中拥有的键。
public enum EventKey
{
OnBark, OnCry
}
public EventHandlerList EventList = new EventHandlerList();
public event ComplaintEventHandler OnBark
{
add
{
EventList.AddHandler(EventKey.OnBark, value);
}
remove
{
EventList.RemoveHandler(EventKey.OnBark, value);
}
}
var handler = EventList[eventKey] as ComplaintEventHandler;
>
handler = null
事实证明它不起作用。但如果我使用声明为(如上所示)的键,它会起作用:
static object EventKeyOnTap = new object();
在阅读了一些 mscorlib 的代码后,我发现问题出next.key == key在
private EventHandlerList.ListEntry Find(object key)
{
EventHandlerList.ListEntry next = this.head;
while (next != null && next.key != key)
{
next = next.next;
}
return next;
}
两个比较的键都来自 my Enum,但它们不相等!我猜它来自一些隐式转换object(存储在列表中的键是 type object),但对这些低级概念不够流畅。
我的猜测对吗?
Enum在 an 中使用 an 作为键的最佳方法是EventHandlerList什么?
现在我将创建我自己EventHandlerList的Enum作为键类型。
现在我EventHandlerList用一个构造函数创建了我自己的Func<object, object, bool>,然后我用它来代替前面提到的相等比较。