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
相关产品推荐
相关产品推荐

