31 c# event-handling
我在一个循环中有一个事件.我试图阻止将同一方法多次添加到事件中.我已经实现了add和remove访问器.
但是,我收到一条错误消息:
ItemsProcessed can only appear on the left hand side of += or -=
当我试着打电话给他们时,即使是在同一个班级里.
ItemsProcessed(this, new EventArgs()); // Produces error
public event EventHandler ItemsProcessed
{
add
{
ItemsProcessed -= value;
ItemsProcessed += value;
}
remove
{
ItemsProcessed -= value;
}
}
Run Code Online (Sandbox Code Playgroud)
Mar*_*ell 30
使用显式事件,您需要提供自己的后备存储 - 代理字段等EventHandlerList.当前代码是递归的.尝试:
private EventHandler itemsProcessed;
public event EventHandler ItemsProcessed
{
add
{
itemsProcessed-= value;
itemsProcessed+= value;
}
remove
{
itemsProcessed-= value;
}
}
Run Code Online (Sandbox Code Playgroud)
然后(并注意到我对"即将转向"边缘情况重新线程有点谨慎null):
var snapshot = itemsProcessed;
if(snapshot != null) snapshot(this, EventArgs.Empty);
Run Code Online (Sandbox Code Playgroud)
使用更新的C#版本,可以简化:
itemsProcessed?.Invoke(this, EventArgs.Empty);
Run Code Online (Sandbox Code Playgroud)
我不能从你的帖子中判断你是否试图从派生类中提取事件,但我发现有一件事是你不能在基类中定义事件然后直接提升它(直接)在派生类中,由于某种原因,我还没有真正清楚.
所以我在基类中定义受保护的函数来引发事件(在那些基类中定义),如下所示:
// The signature for a handler of the ProgressStarted event.
// title: The title/label for a progress dialog/bar.
// total: The max progress value.
public delegate void ProgressStartedType(string title, int total);
// Raised when progress on a potentially long running process is started.
public event ProgressStartedType ProgressStarted;
// Used from derived classes to raise ProgressStarted.
protected void RaiseProgressStarted(string title, int total) {
if (ProgressStarted != null) ProgressStarted(title, total);
}
Run Code Online (Sandbox Code Playgroud)
然后在派生类中,我调用RaiseProgressStarted(title,total)而不是调用ProgressStarted(title,total).
这似乎有点长远.也许其他人知道解决这个问题的更好方法.
| 归档时间: |
|
| 查看次数: |
40153 次 |
| 最近记录: |