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

前端 未结 12 936
囚心锁ツ
囚心锁ツ 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:40

    As others have said, it will only work when T is constrained to be a reference type. Without any constraints, you can compare with null, but only null - and that comparison will always be false for non-nullable value types.

    Instead of calling Equals, it's better to use an IComparer - and if you have no more information, EqualityComparer.Default is a good choice:

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

    Aside from anything else, this avoids boxing/casting.

提交回复
热议问题