-event-只能出现在+的左边或= - = [英] -event- can only appear on the left hand side of += or -=

查看:2105
本文介绍了-event-只能出现在+的左边或= - =的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个循环的事件。我想,以防止被添加到一个事件相同的方法不止一次。我已经实现了添加删除访问。



不过,我得到一个错误,指出:



ItemsProcessed只能出现在左手侧+ =或 - =



当我尝试打电话给他们,即使在同一类。

  ItemsProcessed(这一点,新的EventArgs()); //产生错误

公共事件的EventHandler ItemsProcessed
{

{
ItemsProcessed - =价值;
ItemsProcessed + =价值;
}
拆下
{
ItemsProcessed - =价值;
}
}


解决方案

通过一个明确的事件,您需要提供自己的后备存储 - 无论是代表字段或类似 EventHandlerList 。目前的代码是递归的。尝试:

 私人事件处理itemsProcessed; 
公共事件的EventHandler ItemsProcessed
{

{
itemsProcessed- =价值;
itemsProcessed + =价值;
}

拆下
{
itemsProcessed- =价值;
}
}



然后(并注意到我是一个的谨慎态度即将开启边缘的情况下重新穿线):

  VAR快照= itemsProcessed; 
如果(快照!= NULL)快照(这一点,新的EventArgs());


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;
    }
}

解决方案

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;
        }
    }

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, new EventArgs());

这篇关于-event-只能出现在+的左边或= - =的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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