You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#带IEquatable<T>约束的泛型类使用!=运算符编译报错如何解决?

问题原因
  • IEquatable<T> 接口仅约定类型实现Equals()方法,没有强制要求类型重载==、!=运算符,编译器无法保证所有符合约束的T都支持!=运算,因此抛出编译错误。
解决方案

通用方案(支持值类型+引用类型)

直接调用Equals方法完成判等,使用静态object.Equals()可以自动处理空值避免空引用异常,修改后的代码如下:

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

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

仅适用引用类型的可选方案

如果确认T只会是引用类型,可以额外添加class约束,即可直接使用!=运算符:

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

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

该方案缺点是不支持int、DateTime等值类型,通用性低于第一种方案。

内容的提问来源于stack exchange,提问作者James Screech

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 09:36:02