-event- 只能出现在 += 或 -= 的左侧
我有一个循环事件。我试图防止同一方法多次添加到一个事件中。我已经实现了 add
和 remove
访问器。
但是,我收到一条错误消息:
ItemsProcessed 只能出现在 += 或 -= 的左侧
当我尝试调用它们时,即使在同一个类中也是如此。
ItemsProcessed(this, new EventArgs()); // Produces error
public event EventHandler ItemsProcessed
{
add
{
ItemsProcessed -= value;
ItemsProcessed += value;
}
remove
{
ItemsProcessed -= value;
}
}
I have an event in a loop. I am trying to prevent the same method being added to an event more than once. I've implemented the add
and remove
accessors.
However, I get an error stating that:
ItemsProcessed can only appear on the left hand side of += or -=
When I try to call them, even within the same class.
ItemsProcessed(this, new EventArgs()); // Produces error
public event EventHandler ItemsProcessed
{
add
{
ItemsProcessed -= value;
ItemsProcessed += value;
}
remove
{
ItemsProcessed -= value;
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
对于显式事件,您需要提供自己的后备存储 - 委托字段或类似
EventHandlerList
的内容。当前的代码是递归的。尝试:然后(并注意到我对“即将变为 null”边缘情况重新线程持谨慎态度):
使用更新的 C# 版本,这可以被简化:
With an explicit event, you need to provide your own backing store - either a delegate field or something like
EventHandlerList
. The current code is recursive. Try:Then (and noting I'm being a little cautious about the "about to turn
null
" edge-case re threading):With more recent C# versions, this can be simplified:
我无法从您的帖子中判断您是否试图从派生类引发事件,但我发现的一件事是您无法在基类中定义事件,然后(直接)引发它在派生类中,出于某种原因,我还不太清楚。
因此,我在基类中定义受保护的函数来引发事件(在这些基类中定义),如下所示:
然后在派生类中,我调用 RaiseProgressStarted(title,total) 而不是调用 ProgressStarted(title,total)。
看起来好像绕了很远的路。也许其他人知道解决这个问题的更好方法。
I can't tell from your post if you are trying to raise the event from a derived class or not, but one thing I've found is that you can't define an event in a base class and then raise it (directly) in a derived class, for some reason that isn't real clear to me yet.
So I define protected functions in base classes to raise events (that are defined in those base classes), like this:
Then in the derived class, I call RaiseProgressStarted(title, total) instead of calling ProgressStarted(title, total).
It seems like kind of the long way around. Maybe someone else knows of a better way around this problem.
看来,如果您显式实现
EventHandler
,则在触发事件时无法引用“属性”。您必须参考后备存储。It seems that if you implement the
EventHandler
explicitly, you can't refer to the 'Property' when firing the event. You must refer to the backing store.什么错误?我猜它是堆栈溢出错误,因为您正在自己调用添加和删除(同一事件)。您也不能引发事件 ACCESSOR。
执行此操作的有效方法是创建支持私有事件,该事件将从公共访问器中添加和删除,并且您应该引发此私有事件。
哎呀,迟到了一分钟。
What error? I guess its stack overflow error, because you are calling add and remove on yourserlf (same event). Also you cannot raise event ACCESSOR.
Valid way to do this is to create backing private event, that will be added and removed to from public accessor, and you should raise this private event.
Dang, minute late.