Lambda 表达式:== 与 .Equals()
这是一个纯粹的学术问题,但是在 lambda 表达式中使用 == 和 .Equals 之间有什么区别以及首选哪一个?
代码示例:
int categoryId = -1;
listOfCategories.FindAll(o => o.CategoryId == categoryId);
或
int categoryId = -1;
listOfCategories.FindAll(o => o.CategoryId.Equals(categoryId));
This is a purely academic question, but what's the difference between using == and .Equals within a lambda expression and which one is preferred?
Code examples:
int categoryId = -1;
listOfCategories.FindAll(o => o.CategoryId == categoryId);
or
int categoryId = -1;
listOfCategories.FindAll(o => o.CategoryId.Equals(categoryId));
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
对于引用类型,== 旨在传达引用相等性 - 两个变量是否引用相同对象实例。
.Equals()
旨在传达值相等性 - 对于通过重载方法提供的某些“相同”定义,两个变量引用的两个可能不同的对象实例是否具有相同的值。对于值类型,这两个含义是模糊的。
For reference types, == is intended to communicate reference equality — do the two variables refer to the same object instance.
.Equals()
is intended to communicate value equality — do the two probably different object instances referred to by the two variables have the same value, for some definition of "same" that you provide by overloading the method.For value types, those two meanings are blurred.
它们可以单独重载,因此可以提供不同的答案。请参阅 http://msdn.microsoft.com/en- us/library/ms173147(VS.80).aspx 其中讨论了如何重载每个内容。通常它们是相同的,但不能保证这一点。所以这取决于 lambda 对象是什么类型。
They can be overloaded separately, so they could provide different answers. See http://msdn.microsoft.com/en-us/library/ms173147(VS.80).aspx which discusses how to overload each. Typically they will be the same, but there's no guarantee of that. So it depends on what type the lambda object is.
Lambda 在这里无关紧要...
对于值对象 == 和 equals 是相同的
对于引用对象,如果对象是同一个对象(指向同一个实例),则 == 为 true,而 equals 则期望比较对象的内容。此链接
用另一种方式解释它。
The Lambda is irrelevant here...
For value objects == and equals are the same
For reference object == will be true if the objects are the same object (points to the same instance) while it is expected that equals compare the contents of the objects. This link
explains it in another way.
这取决于为对象定义的内容。如果没有为该类定义运算符 ==,它将使用 Object 类中的运算符,该类在最终调用 Equals() 之前检查 Object.ReferenceEquals。
这显示了一个重要的区别:
如果你说
A.Equals(B)
那么A一定是nun-null。如果你说A == B
,A可能为空。It depends on what defined for the object. If there's no operator== defined for the class, it will use the one from the Object class, which checks Object.ReferenceEquals before eventually calling Equals().
This shows an important distinction:
if you say
A.Equals(B)
then A must be nun-null. if you sayA == B
, A may be null.这在Java 世界中更为突出。基本上“==”是运算符重载和.Equals() 是 Object 类的基本方法。
This is more prominent in the Java world really. Basically '==' is operator overloading and .Equals() is the base method on Object class.