不能将 EventHandler 定义为事件
cannot define EventHandler as event
我需要一个 IDictionary<T,K>
,它在通过 Add
方法添加 item
时引发事件。但是引发的事件应该取决于 item
的键,即如果我将 ("hello","world")
添加到这样的字典中,应该引发 "hello" 事件,如果我添加 ("world","hello")
,那么应该引发 "world"-事件。
所以我尝试实现这个并最终得到
class EventDictionary<T,K> : IDictionary<T,K>
{
private IDictionary<T,K> _internalDic;
private IDictionary<T, EventHandler> _onAddHandlers;
public EventHandler OnAdd(T key)
{
if (!_onAddHandlers.ContainsKey(key))
_onAddHandlers[key] = null;
return _onAddHandlers[key];
}
public void Add(T key, K value)
{
_internalDic.Add(key, value);
OnAdd(key)?.Invoke(this, EventArgs.Empty);
}
public void Add(KeyValuePair<T, K> item)
{
_internalDic.Add(item);
OnAdd(item.Key)?.Invoke(this, EventArgs.Empty);
}
... // implementing the other methods of IDictionary<T,K>
}
这个编译 - 只要我不添加 event
关键字:
private IDictionary<T, event EventHandler> _onAddHandlers; // syntax error
或
public event EventHandler OnAdd(T key) { ... } // syntax error
我是不是漏掉了什么?如何使 OnAdd
事件处理程序(全部)成为 event
s?
无法在您的类型上设置动态数量的事件。事件,就像其他成员(字段、方法、属性)一样,需要在编译时静态定义。所以你可以有你的委托字典,你可以从字典中 add/remove 委托,并在需要时调用这些委托,但它们不会是 class 上的事件;他们需要通过方法,正如您目前所做的那样。
相反,如果您只想拥有一个 单个 事件,其中事件的签名是接受 T
类型参数的事件,那么您在声明您的事件时,只需要使用适当的委托,而不是 EventHandler
:
public event Action<T> OnAdd; // syntax error
我需要一个 IDictionary<T,K>
,它在通过 Add
方法添加 item
时引发事件。但是引发的事件应该取决于 item
的键,即如果我将 ("hello","world")
添加到这样的字典中,应该引发 "hello" 事件,如果我添加 ("world","hello")
,那么应该引发 "world"-事件。
所以我尝试实现这个并最终得到
class EventDictionary<T,K> : IDictionary<T,K>
{
private IDictionary<T,K> _internalDic;
private IDictionary<T, EventHandler> _onAddHandlers;
public EventHandler OnAdd(T key)
{
if (!_onAddHandlers.ContainsKey(key))
_onAddHandlers[key] = null;
return _onAddHandlers[key];
}
public void Add(T key, K value)
{
_internalDic.Add(key, value);
OnAdd(key)?.Invoke(this, EventArgs.Empty);
}
public void Add(KeyValuePair<T, K> item)
{
_internalDic.Add(item);
OnAdd(item.Key)?.Invoke(this, EventArgs.Empty);
}
... // implementing the other methods of IDictionary<T,K>
}
这个编译 - 只要我不添加 event
关键字:
private IDictionary<T, event EventHandler> _onAddHandlers; // syntax error
或
public event EventHandler OnAdd(T key) { ... } // syntax error
我是不是漏掉了什么?如何使 OnAdd
事件处理程序(全部)成为 event
s?
无法在您的类型上设置动态数量的事件。事件,就像其他成员(字段、方法、属性)一样,需要在编译时静态定义。所以你可以有你的委托字典,你可以从字典中 add/remove 委托,并在需要时调用这些委托,但它们不会是 class 上的事件;他们需要通过方法,正如您目前所做的那样。
相反,如果您只想拥有一个 单个 事件,其中事件的签名是接受 T
类型参数的事件,那么您在声明您的事件时,只需要使用适当的委托,而不是 EventHandler
:
public event Action<T> OnAdd; // syntax error