Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
680 views
in Technique[技术] by (71.8m points)

c# - -event- can only appear on the left hand side of += or -=

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;
    }
}
question from:https://stackoverflow.com/questions/4496799/event-can-only-appear-on-the-left-hand-side-of-or

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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, EventArgs.Empty);

With more recent C# versions, this can be simplified:

itemsProcessed?.Invoke(this, EventArgs.Empty);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...