该事件只能出现在+ =或 - =错误的左侧

时间:2017-01-13 19:04:15

标签: c# events event-handling

嗨所以我试图在状态因某些原因而更新时尝试更改此事件,因为它不允许我编译它给出错误:

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

我不知道什么是错的似乎我尝试谷歌它没有帮助

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

感谢你们的时间和帮助!

1 个答案:

答案 0 :(得分:5)

如果有人实施custom events accessor,那么他必须提供支持代理字段,用于存储添加的回调:

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

但为什么它适用于public event Action StateChanged;等标准/非自定义事件?

因为编译器会自动为该事件生成一个支持字段,您可以使用var action = this.StateChanged;获取它,但您应该知道 events are not fields - 它们是一对方法 - add, remove。执行var action = this.StateChanged;时,编译器会根据情况访问事件的自动生成的支持字段