泛型 class 其中类型必须实现 IEquatable

Generic class where type must implement IEquatable

我正在尝试创建一个通用的“属性”class 来保持它的当前值和最后一个值。

public class GenericTrackingProperty<T> where T : IEquatable<T>
{
    private T _oldValue;
    private T _currentValue;

    public T Value
    {
        get { return _currentValue; }
        set
        {
            if (value != _currentValue)
            {
                _oldValue = _currentValue;
                _currentValue = value;
            }
        }
    }
}

尽管在 class 定义中使用 where 来确保泛型类型是等同的,但编译器抱怨比较“if (value != _currentValue”给出错误“运算符'!='不能应用于'T'和'T'类型的操作数”。我做错了什么?

IEquatable<T> doesn't contain operators, but it contains the Equals 方法。
使用它代替相等运算符:

if (!value.Equals(_currentValue))

或者,null 感知:

if (value == null ? _currentValue == null : !value.Equals(_currentValue))

让 .NET compare 为您提供两个值(同时检查 null 等):

if (!EqualityComparer<T>.Default.Equals(value, _currentValue)) {
  ... 
}

您可以使用 value.Equals 但在这种情况下您必须检查 null:

if (value == null && _currentValue != null || !value.Equals(_currentValue)) {
  ...
}