如何解决操作员'!='不能应用于类型的操作数'T'和'T' [英] How to solve Operator '!=' cannot be applied to operands of type 'T' and 'T'

查看:507
本文介绍了如何解决操作员'!='不能应用于类型的操作数'T'和'T'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这段代码按预期工作的 INT 键入:

 公共类的测试{
公共int值
{
{返回_Value; }

{
如果(_Value =价值!)
{
_Value =价值;
}
}
}
私人诠释_Value;
}

INT 是通过普通的 T 更换时,编译器抱怨:




运算符'= 不能应用于类型的操作数'T'和'T'




为什么会出现这种情况,是有解决这个问题的方法?


解决方案

 使用System.Collections.Generic; 

公共类测试< T>
{
公众吨价
{
{返回_Value; }

{
如果(EqualityComparer<!T> .Default.Equals(_Value,值))
{
_Value =价值;
}
}
}
私人牛逼_Value;
}


This code snippet works as expected for the int type:

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

When int is replaced by the generic T, the compiler complains with:

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

Why does this happen and is there a way to solve it?

解决方案

using System.Collections.Generic;

public class Test<T>
{
     public T Value
     {
         get { return _Value; }
         set
         {
             if (!EqualityComparer<T>.Default.Equals(_Value, value))
             {
                 _Value = value;
             }
         }
     }
     private T _Value;
}

这篇关于如何解决操作员'!='不能应用于类型的操作数'T'和'T'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆