Wil*_*iam 14 c# shorthand getter-setter
如果我对这条线的内部运作的理解是正确的:
public int MyInt { get; set; }
Run Code Online (Sandbox Code Playgroud)
然后在幕后做这个:
private int _MyInt { get; set; }
Public int MyInt {
get{return _MyInt;}
set{_MyInt = value;}
}
Run Code Online (Sandbox Code Playgroud)
我真正需要的是:
private bool IsDirty { get; set; }
private int _MyInt { get; set; }
Public int MyInt {
get{return _MyInt;}
set{_MyInt = value; IsDirty = true;}
}
Run Code Online (Sandbox Code Playgroud)
但我想写一些类似于:
private bool IsDirty { get; set; }
public int MyInt { get; set{this = value; IsDirty = true;} }
Run Code Online (Sandbox Code Playgroud)
哪个不起作用.事情是我需要做的一些对象,IsDirty上有几十个属性,我希望有一种方法可以使用auto getter/setter,但是当字段被修改时仍然设置IsDirty.
这是可能的,还是我只需要让自己在我班级中增加三倍的代码?
Ree*_*sey 24
你需要自己处理:
private bool IsDirty { get; set; }
private int _myInt; // Doesn't need to be a property
Public int MyInt {
get{return _myInt;}
set{_myInt = value; IsDirty = true;}
}
Run Code Online (Sandbox Code Playgroud)
没有可用的语法,在仍然使用自动属性机制的同时将自定义逻辑添加到setter.您需要使用自己的支持字段来编写此代码.
这是一个常见问题 - 例如,在实施时INotifyPropertyChanged.
Sim*_*hes 11
创建一个IsDirty装饰器(设计模式)来包装一些需要isDirty标志功能的属性.
public class IsDirtyDecorator<T>
{
public bool IsDirty { get; private set; }
private T _myValue;
public T Value
{
get { return _myValue; }
set { _myValue = value; IsDirty = true; }
}
}
public class MyClass
{
private IsDirtyDecorator<int> MyInt = new IsDirtyDecorator<int>();
private IsDirtyDecorator<string> MyString = new IsDirtyDecorator<string>();
public MyClass()
{
MyInt.Value = 123;
MyString.Value = "Hello";
Console.WriteLine(MyInt.Value);
Console.WriteLine(MyInt.IsDirty);
Console.WriteLine(MyString.Value);
Console.WriteLine(MyString.IsDirty);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
34062 次 |
| 最近记录: |