简体   繁体   English

这两个比较陈述之间有什么区别?

[英]Whats the difference between these two comparison statements?

Whats the difference between these two comparison statments? 这两个比较法的差异是什么?

var result = EqualityComparer<T>.Default.Equals(@this, null);
var result = @this == null;

Obviously the aim is to test whether the object '@this' isnull. 显然,目的是测试对象'@this'是否为空。

Well it depends on the type of @this . 那取决于@this的类型。 If it doesn't have an overload of == , the second line will just perform a direct reference comparison, whereas the first line will call an overridden Equals method or an implementation of IEquatable.Equals . 如果它没有==的重载,第二行将只执行直接引用比较,而第一行将调用重写的 Equals方法或IEquatable.Equals的实现。

Any sensible implementation will give the same result for both comparisons. 任何明智的实施都会给两个比较带来相同的结果。

The first statement calls the Equals() method between objects to see if their values are equal, assuming it has been overriden and implemented in the class T . 第一个语句调用对象之间的Equals()方法,以查看它们的值是否相等,假设它已被覆盖并在类T The second statement compares the references instead, unless the == operator has been overridden like in the String class. 第二个语句比较引用,除非在String类中重写了==运算符。

operator == calls ReferenceEquals on comparing objects, so compare that objects are pointing to the same memory location. operator ==在比较对象时调用ReferenceEquals ,因此请比较这些对象指向相同的内存位置。

Equals , instead, is a just virtual method, so can behave differently for different types, as it can be overriden. Equals ,取而代之的,是一个公正的虚方法,这样可以表现不同的不同的类型,因为它可以被覆盖。

For example, for CLR string Equals compares content of a string and not a reference , even if string is a reference type. 例如,对于CLR string的Equals比较一个的内容 string ,而不是一个参考 ,即使string是引用类型。

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

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