简体   繁体   English

将Object.Equals(Object)与引用类型一起使用

[英]Using Object.Equals(Object) with a reference type

I'm trying to use the method Object.Equals(Object) to compare two different instances of a class I have created but what I need is to compare the value not the reference of the instances. 我正在尝试使用Object.Equals(Object)方法来比较我创建的类的两个不同实例,但我需要的是比较值而不是实例的引用。

Researching about the subject I've found that I need to use value types, like struct, in order to be able to use the method Equals to compare the value of the instances and not the reference but I have a large library of classes so I'm afraid of change their type from class to struct because I don't know what other consequences could it have...any advice about whay should I do? 通过研究该主题,我发现我需要使用诸如struct之类的值类型,以便能够使用Equals方法来比较实例(而不是引用)的值,但是我有一个很大的类库,所以我“我害怕将它们的类型从类更改为结构,因为我不知道它还会带来什么其他后果……我应该怎么做?

Can I override the method Equals for my class so it would compare the values instead the reference? 我可以覆盖类的Equals方法,以便比较值而不是引用吗? I know it would be a lot of ways to do ir but what's the one that will give the best performance and " programming correction "...? 我知道有很多方法可以解决问题,但是哪种方法可以提供最佳性能和“ 编程更正 ” ...?

Yes, you have to override the Equals method and == operator of your class and in that write your comparison logic. 是的,您必须重写类的Equals方法和==运算符,然后编写比较逻辑。

For more read 欲了解更多信息
Guidelines for Overloading Equals() and Operator == (C# Programming Guide) 重载Equals()和运算符==的准则(C#编程指南)

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

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