Lambda表达式:==与.Equals() [英] Lambda Expression: == vs. .Equals()

查看:941
本文介绍了Lambda表达式:==与.Equals()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个纯粹的学术问题,但什么是使用之间的==和.Equals lambda表达式中的差异,其中之一是首选?



代码示例:



  INT的categoryId = -1; 
listOfCategories.FindAll(O => o.CategoryId ==的categoryId);



  INT的categoryId = -1; 
listOfCategories.FindAll(O => o.CategoryId.Equals(的categoryId));


解决方案

有关引用类型,==是为了沟通参考平等—做两个的变量的参考的相同的对象实例。结果
.Equals()是为了沟通值相等—做提到了两个变量具有相同的值,为的相同的一些定义您通过重载方法提供两种可能不同的对象实例



有关值类型,这两种含义是模糊的。


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));

解决方案

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.

这篇关于Lambda表达式:==与.Equals()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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