嗨所以我试图让这个事件发生变化,因为某些原因状态更新它不允许我编译它给出错误:
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; } }
谢谢你们的时间和帮助!
如果实现自定义事件访问器,则必须提供将用于存储添加的回调的支持委托字段:
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;
,但您应该知道事件不是字段 - 它们是一对方法 - add, remove
.这是上下文访问事件的自动生成的编译器支持字段,当你做var action = this.StateChanged;
.