Operator '==' can't be applied to type T?

倾然丶 夕夏残阳落幕 提交于 2019-12-01 02:54:01

Good for you for reading the spec, but you stopped reading too soon. Had you read further you would have gotten to this bit:


The predefined reference type equality operators require one of the following:

  • Both operands are a value of a type known to be a reference-type or the literal null. Furthermore, an explicit reference conversion exists from the type of either operand to the type of the other operand.

  • One operand is a value of type T where T is a type-parameter and the other operand is the literal null. Furthermore T does not have the value type constraint.

Unless one of these conditions are true, a binding-time error occurs. (*)


The error isn't from overload resolution; the error is that overload resolution would have chosen the predefined reference type equality operator, and you don't have reference types.

Consider your code. What stops T from being a value type with no equality operator defined on it? Nothing. Suppose we fell back to the object version; both operands would box to different locations and therefore be reference-unequal, even if they had the same content. Since that is slow, confusing and wrong, it is illegal to even try.

Why are you trying to do this thing in the first place? If your method worked, which it doesn't, then your method would be worse than simply using == in the first place. What is the value you intend to add to the world with this method?


(*) I've reported the grammatical error in this sentence to the spec maintainers.

That would possibly work if it knew that where T : class, doing a reference comparison. Operators generally have very little support with generics, but there are workarounds. MiscUtil offers indirect support for operators on generics, otherwise EqualityComparer<T>.Default.Equals(x,y) is a good choice.

I like using EqualityComparer<T>.Default for this.

It is based on the overridden Equals method, but uses IEquatable<T> when available, avoiding boxing on value types implementing it.

EqualityComparer<T>.Default.Equals(x, y)

use .Equals() method and be sure that the T implement IComparable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!