例子:
public class Base : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName)
{
var handler = PropertyChanged;
if (handler != null)
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
public class Descendent : Base
{
public Descendent()
{
DetermineDefaultMyPropertyValue();
}
public string MyProperty { get; set; }
private void DetermineDefaultMyPropertyValue()
{
MyProperty = "Default value";
}
protected override void OnPropertyChanged(string propertyName)
{
// some property changed logic
}
}
可以通过将自动实现的属性更改为使用支持字段来解决此问题。(仅在构造对象时设置的那些。)
public class Descendent : Base
{
public Descendent()
{
DetermineDefaultMyPropertyValue();
}
private string _myProperty;
public string MyProperty {
get { return _myProperty; }
set { _myProperty = value; }
}
private void DetermineDefaultMyPropertyValue()
{
_myProperty = "Default value";
}
protected override void OnPropertyChanged(string propertyName)
{
// some property changed logic
}
}