是否有必要重写==和!=运算符重载Equals方法是什么时候? (。净) [英] Is it necessary to override == and != operators when overriding the Equals method? (.NET)

查看:233
本文介绍了是否有必要重写==和!=运算符重载Equals方法是什么时候? (。净)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

或者它的最好做呢? 为什么呢?

Or it's advisable to do that? Why?

推荐答案

见重写等于指引( )和运营商==

报价:

在默认情况下,运营商==通过确定两个引用是否表示同一个对象测试引用相等。因此,引用类型没有实现,以获得此功能的==操作符。当一个类型是不可变的,即,包含在该实例中的数据不能被改变,重载operator ==来比较值相等,代替参考平等可以是有用的,因为,如不可变对象,它们可以被认为是相同的,只要因为它们具有相同的值。这不是一个好主意,覆盖运营商==非不可变的类型。

By default, the operator == tests for reference equality by determining whether two references indicate the same object. Therefore, reference types do not have to implement operator == in order to gain this functionality. When a type is immutable, that is, the data that is contained in the instance cannot be changed, overloading operator == to compare value equality instead of reference equality can be useful because, as immutable objects, they can be considered the same as long as they have the same value. It is not a good idea to override operator == in non-immutable types.

基本上是:

如果你想==和!=的行为类似于等于(..)!等于(..)您需要实现运营商。您通常这样做只与不变类型。

If you want == and != to behave like Equals(..) and !Equals(..) you need to implement the operators. You typically do this only with immutable types.

这篇关于是否有必要重写==和!=运算符重载Equals方法是什么时候? (。净)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆