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

后端 未结 4 1345
伪装坚强ぢ
伪装坚强ぢ 2021-01-11 12:21

I thought this method was valid but I was wrong:

static void Equals(T x, T y)
{
    return x == y;    //operator == can\'t be applied to type T
}


        
相关标签:
4条回答
  • 2021-01-11 13:03

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

    0 讨论(0)
  • 2021-01-11 13:13

    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.

    0 讨论(0)
  • 2021-01-11 13:14

    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.

    0 讨论(0)
  • 2021-01-11 13:24

    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)
    
    0 讨论(0)
提交回复
热议问题