[英]C# Enums and Generics
Why does the compiler reject this code with the following error? 为什么编译器拒绝此代码时出现以下错误? (I am using VS 2017
with C# 7.3
enabled.) (我使用的是VS 2017
,启用了C# 7.3
。)
CS0019 Operator '==' cannot be applied to operands of type 'T' and 'T' CS0019运算符'=='不能应用于'T'和'T'类型的操作数
public class GenericTest<T> where T : Enum
{
public bool Compare(T a, T b)
{
return a == b;
}
}
The version without generics is of course perfectly valid. 没有泛型的版本当然是完全有效的。
public enum A { ONE, TWO, THREE };
public class Test
{
public bool Compare(A a, A b)
{
return a == b;
}
}
The compiler cannot rely on the operator ==
being implemented for every type provided for T
. 编译器不能依赖于为T
提供的每种类型实现的运算符==
。 You could add a constraint to restrict T
to class
, but that would not allow you to use it for your enum, due to the enum not being a reference type. 您可以添加一个约束来限制T
到class
,但由于枚举不是引用类型,因此不允许您将它用于枚举。 Adding struct
as a constraint would also not allow you to use the operator because structs don't always have an implementation of the ==
operator, but you could use a.Equals(b)
in that case instead. 添加struct
作为约束也不允许使用运算符,因为结构并不总是具有==
运算符的实现,但在这种情况下你可以使用a.Equals(b)
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.