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

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

    The compile can't know T couldn't be a struct (value type). So you have to tell it it can only be of reference type i think:

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

    It's because if T could be a value type, there could be cases where x == y would be ill formed - in cases when a type doesn't have an operator == defined. The same will happen for this which is more obvious:

    void CallFoo(T x) { x.foo(); }
    

    That fails too, because you could pass a type T that wouldn't have a function foo. C# forces you to make sure all possible types always have a function foo. That's done by the where clause.

提交回复
热议问题