事件委托(in)平等?
有人可以解释以下代码部分的含义吗:
private event UserChangedHandler m_UserChanged;
public event UserChangedHandler UserChanged
{
add
{
if (m_UserChanged != value)
{
m_UserChanged += value;
}
}
}
谢谢
Could someone explain the meaning of the following portion of code :
private event UserChangedHandler m_UserChanged;
public event UserChangedHandler UserChanged
{
add
{
if (m_UserChanged != value)
{
m_UserChanged += value;
}
}
}
thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
add { }
的结构与属性的get { }
非常相似,只不过 add 适用于事件。将委托添加到事件时,您可以在此处定义自定义功能。在这种情况下,此方法主体可以防止连续重复(即您不能连续注册相同的方法/处理程序两次)。
因此,在此示例中:
稍后:
方法
HandleUserChanged
只会触发一次,即使您注册了两次。正常事件(没有add { }
)会调用该函数两次。但是:
将允许
HandleUserChanged
触发两次,因为最后注册的处理程序永远不是添加的处理程序。事件上的 == 运算符适用于 LAST 处理程序。 (感谢马修让我们注意到这一点)add { }
is a construct much likeget { }
for properties, except add works on events. You're defining custom functionality here when adding delegates to an event.In this case, this method body prevents consecutive duplicates (i.e. you can't register the same method/handler twice in a row).
So in this example:
Later:
The method
HandleUserChanged
will only fire once, even though you registered it twice. A normal event (without theadd { }
) would invoke the function twice.However:
Will allow
HandleUserChanged
to fire twice, because the last-registered handler isn't ever the one being added. The == operator on events works on the LAST handler. (Thankyou to Matthew for bringing that to attention)让我感到奇怪的是,m_UserChanged 被声明为一个事件而不仅仅是一个委托实例(这是正确的术语......我对委托感到困惑)。事件类似于简单的属性模型,因为它们本质上将底层字段包装在一对透明方法中。
按照我的理解,.Net 允许通过以下方式创建隐式(匿名?)事件和属性:
然后创建相应的底层占位符对象以生成更像这样的内容:
底层对象可以显式定义为当然,但是上面的代码示例看起来像是显式事件声明和隐式事件声明之间的一些合并...看起来实际上正在完成以下操作(可以说是在幕后):
这并不重要从总体上看,我不这么认为,但这看起来像是一个疏忽。
It strikes me as odd that m_UserChanged is declared as an event rather than just a delegate instance (is that the right terminology...I get confused w/ delegates). Events are analogous to a simple Property model in that they essentially wrap underlying fields within a pair of transparent methods.
The way I understand it, .Net allows for the creation of implcit (anonymous?) event and properties by taking something like this :
and then creating the respective underlying placeholder objects to generate something more like this:
The underlying object can be defined explicitly of course, but what the code sample above looks like is a bit of a conflation between explicit and implicit event declaration...it looks like the following is actually being done (behind the scenes, as it were):
It doesn't really matter in the grand scheme of things, I don't guess, but it looks like an oversight.