-event- can only appear on the left hand side of += or -=(-event- 只能出现在 += 或 -= 的左侧)
问题描述
我有一个循环中的事件.我试图防止将相同的方法多次添加到事件中.我已经实现了 add 和 remove 访问器.
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 只能出现在 += 或 -= 的左侧
当我尝试打电话给他们时,即使在同一个班级.
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;
}
}
推荐答案
对于显式事件,您需要提供自己的后备存储 - 委托字段或类似 EventHandlerList 的东西.当前代码是递归的.试试:
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:
private EventHandler itemsProcessed;
public event EventHandler ItemsProcessed
{
add
{
itemsProcessed-= value;
itemsProcessed+= value;
}
remove
{
itemsProcessed-= value;
}
}
然后(注意到我对即将转为 null"边缘情况重新线程处理持谨慎态度有点):
Then (and noting I'm being a little cautious about the "about to turn null" edge-case re threading):
var snapshot = itemsProcessed;
if(snapshot != null) snapshot(this, EventArgs.Empty);
使用最新的 C# 版本,这可以简化:
With more recent C# versions, this can be simplified:
itemsProcessed?.Invoke(this, EventArgs.Empty);
这篇关于-event- 只能出现在 += 或 -= 的左侧的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:-event- 只能出现在 += 或 -= 的左侧
基础教程推荐
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
- 全局 ASAX - 获取服务器名称 2022-01-01
- 如何动态获取文本框中datagridview列的总和 2022-01-01
- JSON.NET 中基于属性的类型解析 2022-01-01
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01
