Skip to main content
 首页 » 编程设计

C#/WinForms/INotifyPropertyChanged : Elegant way to check for equality when either or both operands might be null

2024年02月23日13kevingrace

我有一个实现 INotifyPropertyChanged 的​​类 Bar。设置属性 CurrentFoo 时,我想在值发生变化时引发 PropertyChanged。 Foo 实现 IEquatable 但不实现 == 运算符。

目前我的代码是这样的:

public class Bar : INotifyPropertyChanged 
{ 
    // ... 
 
    private Foo fooValue; 
 
    /// <summary> 
    /// Gets or sets the active Foo 
    /// </summary> 
    /// <value>The active Foo.</value> 
    public Foo CurrentFoo 
    { 
        get 
        { 
            return this.fooValue; 
        } 
 
        set 
        { 
            // Notify listeners if value is changing. 
            if (null == this.fooValue && null != value 
                || null != this.fooValue && null == value 
                || null != this.fooValue && null != value && !this.fooValue.Equals(value)) 
            { 
                this.fooValue = value; 
                this.OnPropertyChanged("CurrentFoo"); 
            } 
        } 
    } 
 
   // ... 
} 

它确实有效,但是......呃!是否有更优雅/最佳实践的方式来执行此检查而不恢复到 Null 对象模式(与我们的代码库的其余部分不一致)?

我考虑过编写一个实用程序方法,例如 IsOneObjectNullButNotBoth(object a, object b)...但是,又一次,废话。我肯定缺少一个方便的类库方法,尽管我已经检查过了。

请您参考如下方法:

测试其中一个值是否为 null 就足够了,因为如果参数为 null,Equals 方法应该返回 false:

if ((this.fooValue != value) || 
    (this.fooValue != null && !this.fooValue.Equals(value))) 
{ 
    this.fooValue = value; 
    this.OnPropertyChanged("CurrentFoo"); 
} 

或者,您可以为 Foo 使用默认的 EqualityComparer,它检查空值并调用 Equals 方法:

if (!EqualityComparer<Foo>.Default.Equals(this.FooValue, value)) 
{ 
    this.fooValue = value; 
    this.OnPropertyChanged("CurrentFoo"); 
}