C# 如何解决运算符 '!=' 不能应用于类型为 'T' 和 'T' 的操作数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8982645/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to solve Operator '!=' cannot be applied to operands of type 'T' and 'T'
提问by Darf
This code snippet works as expected for the inttype:
此代码片段按预期工作的int类型:
public class Test
{
public int Value
{
get => _Value;
set
{
if (_Value != value)
_Value = value;
}
}
private int _Value;
}
When intis replaced by the generic T, the compiler complains with:
当int被 generic 替换时T,编译器会抱怨:
Operator '!=' cannot be applied to operands of type 'T' and 'T'
运算符 '!=' 不能应用于类型为 'T' 和 'T' 的操作数
Why does this happen and is there a way to solve it?
为什么会发生这种情况,有没有办法解决?
回答by leppie
Tcan be any type. You cannot use ==/!=on structs, unless such operators are defined on the (struct) type.
T可以是任何类型。您不能在结构上使用==/ !=,除非在 (struct) 类型上定义了此类运算符。
回答by user541686
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;
}
回答by gdoron is supporting Monica
Tis a type argument and can be a classor a struct, Thus compiler won't let you perform actions that doesn't exist in classes and structs.
T是一个类型参数,可以是 aclass或 a struct,因此编译器不会让您执行类和结构中不存在的操作。
structs don't have the == and != by default(but can be added), this is why the compiler complains.
默认情况下,结构没有 == 和 !=(但可以添加),这就是编译器抱怨的原因。
If you use the wherekeyword to add a constraint to the type argument, the Compiler will let you use that type\interface method\operators
如果您使用where关键字向类型参数添加约束,编译器将允许您使用该类型\接口方法\运算符
constrain Tto be a class
约束T为class
public class Test<T> where T : class
{
public T Value
{
private T _Value;
get { return _Value; }
set
{
if (_value != value)
_Value = value;
}
}
}
Or simply use Equalsinstead of the ==operator
或者干脆使用Equals代替==操作符
public class Test<T>
{
public T Value
{
private T _Value;
get { return _Value; }
set
{
if (!_value.Equals(value)
_Value = value;
}
}
}

