Can't operator == be applied to generic types in C#?

前端 未结 12 672
囚心锁ツ
囚心锁ツ 2020-11-22 02:21

According to the documentation of the == operator in MSDN,

For predefined value types, the equality operator (==) returns true if th

12条回答
  •  自闭症患者
    2020-11-22 02:31

    It appears that without the class constraint:

    bool Compare (T x, T y) where T: class
    {
        return x == y;
    }
    

    One should realize that while class constrained Equals in the == operator inherits from Object.Equals, while that of a struct overrides ValueType.Equals.

    Note that:

    bool Compare (T x, T y) where T: struct
    {
        return x == y;
    }
    

    also gives out the same compiler error.

    As yet I do not understand why having a value type equality operator comparison is rejected by the compiler. I do know for a fact though, that this works:

    bool Compare (T x, T y)
    {
        return x.Equals(y);
    }
    

提交回复
热议问题