<分区>
对于值类型、引用类型和字符串,a.Equals(b)
和a == b
之间有什么区别?似乎 a == b 对字符串工作得很好,但我正在尝试确保使用良好的编码实践。
<分区>
对于值类型、引用类型和字符串,a.Equals(b)
和a == b
之间有什么区别?似乎 a == b 对字符串工作得很好,但我正在尝试确保使用良好的编码实践。
最佳答案
来自 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));
}
}
这个简短示例程序的结果是
True
True
False
True
关于c# - .Equals 和 == 有什么区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/772953/