该事件只能出现在+ =或-=错误的左侧 [英] The event can only appear on the left hand side of += or -= error
问题描述
您好,我试图在状态更新时更改此事件,原因是出于某种原因,它不允许我进行编译,这会导致错误:
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 -=
我不知道这是怎么回事,我尝试使用google并没有帮助
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;
}
}
感谢您的时间和帮助!
推荐答案
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;
}
}
但是为什么它可以与public event Action StateChanged;
之类的标准/非自定义事件一起使用?
But why does it work with standard/non-custom events like public event Action StateChanged;
?
因为编译器会自动为该事件生成一个后备字段,您可以通过var action = this.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;
.
这篇关于该事件只能出现在+ =或-=错误的左侧的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!