C#中:事件明确地添加/删除=典型的事件!? [英] C#: event with explicity add/remove != typical event?

查看:160
本文介绍了C#中:事件明确地添加/删除=典型的事件!?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经声明了一个通用的事件处理程序

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();只有语法糖,其可以是仅pdicated如果事件被隐含实施$ P $

The "ExplicitEvent.RaiseEvent();" is only syntax sugar, which can be predicated only if the event is implicitly implemented.

这篇关于C#中:事件明确地添加/删除=典型的事件!?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆