使用CodeContracts强制正确实现INotifyPropertyChanged - "需要未经证实"

hwi*_*ers 5 c# inotifypropertychanged code-contracts

我正在寻找一种简单的方法来强制正确实现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;
}
Run Code Online (Sandbox Code Playgroud)

反正有没有让这个工作?

Mar*_*ell 1

我想你的意思是静态分析工具?(我希望运行时检查至少能够工作 - 并且您可能可以将其保留在调试版本中)。我怀疑这是静态分析能够看穿的东西——GetType().GetProperties()太复杂了,等等。

简而言之; 我对此表示怀疑... lambda ( Expression) 是一种选择,但它们比仅传递字符串要慢得多。