When would == be overridden in a different way to .equals?

后端 未结 4 1001
旧巷少年郎
旧巷少年郎 2020-12-16 14:32

I understand the difference between == and .equals. There are plenty of other questions on here that explain the difference in detail e.g. this one: What is the difference

4条回答
  •  鱼传尺愫
    2020-12-16 14:38

    == is bound statically, at compile-time, because operators are always static. You overload operators - you can't override them. Equals(object) is executed polymorphically, because it's overridden.

    In terms of when you'd want them to be different...

    Often reference types will override Equals but not overload == at all. It can be useful to easily tell the difference between "these two references refer to the same object" and "these two references refer to equal objects". (You can use ReferenceEquals if necessary, of course - and as Eric points out in comments, that's clearer.) You want to be really clear about when you do that, mind you.

    double has this behavior for NaN values; ==(double, double) will always return false when either operand is NaN, even if they're the same NaN. Equals can't do that without invalidating its contract. (Admittedly GetHashCode is broken for different NaN values, but that's a different matter...)

    I can't remember ever implementing them to give different results, personally.

提交回复
热议问题