简体   繁体   English

比较参考类型(C#)

[英]Comparing reference types (C#)

I need to compare the values of some reference types that I've created. 我需要比较一下我创建的一些引用类型的值。 Which should I override, the Object.Equals method or the == operator? 我应该覆盖哪些,Object.Equals方法或==运算符? I'm guessing that Object.Equals is the right way to go since I'm not comparing the references themselves. 我猜测Object.Equals是正确的方法,因为我没有比较引用本身。

You should override the Equals() method (and most likely GetHashCode() method as well, to preserve the equivalence) 你应该重写Equals()方法(也很可能是GetHashCode()方法,以保持等价)

public override bool Equals(object obj) { ... }

public override int GetHashCode() { ... }

Please see the msdn reference on the topic 请参阅有关该主题的msdn参考

Also see this possible duplicate 另见这可能重复

To go along with what karim said, I recommend you follow the MSDN guidelines for overloading the Equals operator, as well as overload the == operator. 为了配合karim所说的内容,我建议您遵循MSDN指南来重载Equals运算符,以及重载==运算符。 This gives you a bit more flexibility on your future usage. 这为您未来的使用提供了更多灵活性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM