C#:显式添加/删除事件!= 典型事件? [英] C#: event with explicity add/remove != typical event?
问题描述
我已经声明了一个通用的事件处理程序
I have declared a generic event handler
public delegate void EventHandler();
我添加了扩展方法RaiseEvent":
to which I have added the extension method 'RaiseEvent':
public static void RaiseEvent(this EventHandler self) {
if (self != null) self.Invoke();
}
当我使用典型语法定义事件时
When I define the event using the typical syntax
public event EventHandler TypicalEvent;
然后我可以毫无问题地调用使用扩展方法:
then I can call use the extension method without problems:
TypicalEvent.RaiseEvent();
但是当我使用显式添加/删除语法定义事件时
But when I define the event with explicit add/remove syntax
private EventHandler _explicitEvent;
public event EventHandler ExplicitEvent {
add { _explicitEvent += value; }
remove { _explicitEvent -= value; }
}
那么扩展方法不存在于使用显式添加/删除语法定义的事件上:
then the extension method does not exist on the event defined with explicit add/remove syntax:
ExplicitEvent.RaiseEvent(); //RaiseEvent() does not exist on the event for some reason
当我将鼠标悬停在事件上以查看其原因时:
And when I hover over to event to see the reason it says:
事件 'ExplicitEvent' 只能出现在 += 的左侧或-=
The event 'ExplicitEvent' can only appear on the left hand side of += or -=
为什么使用典型语法定义的事件与使用显式添加/删除语法定义的事件不同,为什么扩展方法不适用于后者?
我发现我可以通过直接使用私有事件处理程序来解决它:
_explicitEvent.RaiseEvent();
但我仍然不明白为什么我不能像使用典型语法定义的事件那样直接使用该事件.也许有人可以启发我.
But I still don't understand why I cannot use the event directly like the event defined using the typical syntax. Maybe someone can enlighten me.
推荐答案
因为你可以这样做(它是非现实世界的示例,但它有效"):
Because you can do this (it's non-real-world sample, but it "works"):
private EventHandler _explicitEvent_A;
private EventHandler _explicitEvent_B;
private bool flag;
public event EventHandler ExplicitEvent {
add {
if ( flag = !flag ) { _explicitEvent_A += value; /* or do anything else */ }
else { _explicitEvent_B += value; /* or do anything else */ }
}
remove {
if ( flag = !flag ) { _explicitEvent_A -= value; /* or do anything else */ }
else { _explicitEvent_B -= value; /* or do anything else */ }
}
}
编译器如何知道它应该用ExplicitEvent.RaiseEvent();"做什么?答:不能.
How can the compiler know what it should do with "ExplicitEvent.RaiseEvent();"? Answer: It can't.
ExplicitEvent.RaiseEvent();"只是语法糖,只有隐式实现了事件才能断言.
The "ExplicitEvent.RaiseEvent();" is only syntax sugar, which can be predicated only if the event is implicitly implemented.
这篇关于C#:显式添加/删除事件!= 典型事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!