我正在寻找一种简单的方法来强制执行 INotifyPropertyChanged 的正确实现,即当 PropertyChanged 被引发时,它必须引用实际定义的属性。我尝试使用 Microsoft 的新 CodeContract 工具执行此操作,但我不断收到警告“CodeContracts:需要未经证实”。这是我的代码...
public sealed class MyClass : INotifyPropertyChanged
{
private int myProperty;
public int MyProperty
{
get
{
return myProperty;
}
set
{
if (myProperty == value)
{
return;
}
myProperty = value;
OnPropertyChanged("MyProperty");
}
}
private void OnPropertyChanged(string propertyName)
{
Contract.Requires(GetType().GetProperties().Any(x => x.Name == propertyName));
var handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
public event PropertyChangedEventHandler PropertyChanged;
}
反正有没有让这个工作?