The event can only appear on the left hand side of += or -= error

只愿长相守 提交于 2020-01-15 04:02:05

问题


Hi so am trying to make this event change when the state is updated for some reason it's not allowing me to compile it's giving the error:

The event 'Entity.StateChanged' can only appear on the left hand side of += or -=

I don't know what's wrong it seems right i tried google it did not help

public Entity.State state
{
    get
    {
        return this._state;
    }
    set
    {
        if (this._state != value)
        {
            this._state = value;
            this.OnStateChanged();
        }
    }
}

protected virtual void OnStateChanged()
{
    if (this.StateChanged != null)
    {
        this.StateChanged();
    }
}

public event Action StateChanged
{
    [MethodImpl(MethodImplOptions.Synchronized)]
    add
    {
        this.StateChanged += value;
    }
    [MethodImpl(MethodImplOptions.Synchronized)]
    remove
    {
        this.StateChanged -= value;
    }
}

Thank you guy's for your time and help!


回答1:


If one implements custom events accessor, then he has to provide a backing delegate field that will be used to store added callbacks:

protected virtual void OnStateChanged()
{
    var stateChanged = this._stateChanged;
    if (stateChanged == null)
        return;

    stateChanged();
}

private Action _stateChanged;

public event Action StateChanged
{
    [MethodImpl(MethodImplOptions.Synchronized)]
    add
    {
        this._stateChanged += value;
    }
    [MethodImpl(MethodImplOptions.Synchronized)]
    remove
    {
        this._stateChanged -= value;
    }
}

But why does it work with standard/non-custom events like public event Action StateChanged;?

Because compiler automatically generates a backing field for that event and you can get get it with var action = this.StateChanged;, but you should know that events are not fields - they are a pair of methods - add, remove. It is the compiler that contextually accesses event's autogenerated backing field when you do var action = this.StateChanged;.



来源:https://stackoverflow.com/questions/41641716/the-event-can-only-appear-on-the-left-hand-side-of-or-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!