-event-只能出现在+ =或 - =的左侧

31 c# event-handling

我在一个循环中有一个事件.我试图阻止将同一方法多次添加到事件中.我已经实现了addremove访问器.

但是,我收到一条错误消息:

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)

  • @Nyerguds子类化很少有*良好的理由来访问支持字段; 在事件的情况下,更常见的方法是`protected virtual void OnItemsProcessed()=> itemsProcessed?.Invoke(this,EventArgs.Empty);` - 完成工作,不需要公开对该字段的访问 (3认同)
  • 缺点:只能在一个班级内访问 (2认同)
  • 为什么要访问课外的私人支持事件? (2认同)

小智 9

似乎如果你EventHandler明确地实现了,那么在触发事件时你不能引用'Property'.您必须参考后备存储.


Sha*_*ais 9

我不能从你的帖子中判断你是否试图从派生类中提取事件,但我发现有一件事是你不能在基类中定义事件然后直接提升它(直接)在派生类中,由于某种原因,我还没有真正清楚.

所以我在基类中定义受保护的函数来引发事件(在那些基类中定义),如下所示:

// 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).

这似乎有点长远.也许其他人知道解决这个问题的更好方法.

  • 呵呵,我刚刚又遇到了这个问题,不太记得是什么原因造成的以及我是如何修复它的,并在 11 个月前找到了我自己的答案。这很有趣。 (3认同)
  • 现在是 2019 年,这解决了我的问题,感谢 2015 年关于 2010 年问题的帖子!:-D (2认同)