.Equals之间的区别是什么== [英] What is the difference between .Equals and ==
问题描述
(二)和 A == b
值类型,引用的 a.Equals的区别是什么类型和字符串类型?这似乎就像一个== B工作蛮好的字符串,但我想一定要使用良好的编码习惯。
equals方法仅仅是一个虚拟的 之一System.Object的定义,和 通过取其类选择覆盖 这样做。 ==操作符是一个 操作者可以通过被重载 类,但通常有 身份的行为。
有关引用类型,其中==还没有 被超载,它比较是否 两个引用指的是同 对象 - 这正是 实施的Equals确实在 System.Object的。
值类型不提供过载 对于==默认。然而,大多数 由提供的值类型 框架提供自己的过载。 的Equals的默认实现 为一个值类型是由提供 值类型,并使用反射来使 的比较,这使得它 比显著慢 类型具体执行正常 将会。此实现还 电话等于在对引用 内被比较的两个值
使用系统;
公共类测试
{
静态无效的主要()
{
//创建两个相同,但不同的弦
字符串=新的字符串(新的char [] {'H','E','L','L','O'});
字符串B =新的字符串(新的char [] {'H','E','L','L','O'});
Console.WriteLine(A == B);
Console.WriteLine(a.Equals(B));
//现在让我们看看使用相同的测试,会发生什么,但
//有类型的对象变量
对象C = A;
物D = B;
Console.WriteLine(C = D);
Console.WriteLine(c.Equals(d)条);
}
}
这短短的示例程序的结果是
真
真正
假
真正
What is the difference between a.Equals(b)
and a == b
for value types, reference types, and strings? It would seem as though a == b works just fine for strings, but I'm trying to be sure to use good coding practices.
From When should I use Equals and when should I use ==:
The Equals method is just a virtual one defined in System.Object, and overridden by whichever classes choose to do so. The == operator is an operator which can be overloaded by classes, but which usually has identity behaviour.
For reference types where == has not been overloaded, it compares whether two references refer to the same object - which is exactly what the implementation of Equals does in System.Object.
Value types do not provide an overload for == by default. However, most of the value types provided by the framework provide their own overload. The default implementation of Equals for a value type is provided by ValueType, and uses reflection to make the comparison, which makes it significantly slower than a type-specific implementation normally would be. This implementation also calls Equals on pairs of references within the two values being compared.
using System;
public class Test
{
static void Main()
{
// Create two equal but distinct strings
string a = new string(new char[] {'h', 'e', 'l', 'l', 'o'});
string b = new string(new char[] {'h', 'e', 'l', 'l', 'o'});
Console.WriteLine (a==b);
Console.WriteLine (a.Equals(b));
// Now let's see what happens with the same tests but
// with variables of type object
object c = a;
object d = b;
Console.WriteLine (c==d);
Console.WriteLine (c.Equals(d));
}
}
The result of this short sample program is
True
True
False
True
这篇关于.Equals之间的区别是什么==的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!