目前为了使setter也设置一个脏属性我必须做这样的事情:
private bool _isDirty;
private int _lives;
public int Lives{
get { return _lives; }
set {
if (_lives != value){
_lives = value;
_isDirty = true;
}
}
}
Run Code Online (Sandbox Code Playgroud)
写这不是一个巨大的痛苦,但如果我在我的项目中使用了相当多的这种模式,那么这是一个非常垂直且重复的代码.
在C#中有没有任何简写或替代,更短的语法?
我特别想要完成的是某些变量应该触发一个脏标志,在代码的渲染阶段可以用它来刷新渲染对象的属性.
小智 7
创建一个实现辅助方法的类.
class DirtyClass
{
protected bool IsDirty { get; set;}
protected void ChangeProperty<T>(ref T backing, T Value)
{
if(!backing.Equals(value))
{
backing = value;
IsDirty = true;
}
}
}
Run Code Online (Sandbox Code Playgroud)
在setter中使用辅助方法
class LivesCounter : DirtyClass
{
private int _lives;
public int Lives
{
get { return _lives; }
set { ChangeProperty(ref _lives, value); }
}
}
Run Code Online (Sandbox Code Playgroud)
处理null元素留作练习.
正如jdl134679所提到的,请查看INotifyPropertyChanged接口.