c# - 如何解决Operator '!=' cannot be applyed to operands of type 'T' and 'T'

标签 c# generics

<分区>

对于 int 类型,此代码片段按预期工作:

public class Test 
{
    public int Value
    {
        get => _Value;
        set
        {
            if (_Value != value)
                _Value = value;
        }
    }
    private int _Value;
}

int 被通用的 T 替换时,编译器会报错:

Operator '!=' cannot be applied to operands of type 'T' and 'T'

为什么会出现这种情况,有什么办法可以解决吗?

最佳答案

using System.Collections.Generic;

public class Test<T>
{
    public T Value
    {
         get => _Value; 
         set
         {
            // operator== is undefined for generic T; EqualityComparer solves this
            if (!EqualityComparer<T>.Default.Equals(_Value, value))
            {
                _Value = value;
            }
         }
    }
    private T _Value;
}

关于c# - 如何解决Operator '!=' cannot be applyed to operands of type 'T' and 'T',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8982645/

相关文章:

c# - 当尝试写入文件抛出 UnauthorizedAccessException 时,需求不会抛出异常

c# - 如何遍历 X 和 Y 的所有可能组合

java - java中泛型类型的子类型

java - 将泛型类传递给 java 函数?

java - 类从泛型父类(super class)扩展但不指定泛型类型

c# - System.Drawing.Color 与 TypeNameHandling 的 JSON.NET 序列化

c# - 返回列表 1 和列表 2 中的项目匹配的列表

c# - 在没有 IOC 的情况下管理 wcf 服务中的 DbContext 范围?

java - 当您可以只使用具体类型时,为什么会有带有上限的通配符?

Scala:泛型和隐式