关于.net:C中==和Equals之间的差异#

Difference between == and Equals in C#

本问题已经有最佳答案,请猛点这里访问。

Possible Duplicate:
C# difference between == and .Equals()

为了比较两个变量,我们可以使用==或等于方法。例如,

1
2
3
4
5
        string a = new string(new char[] {'a', 'b', 'c', 'd'});
        string b = new string(new char[] {'a', 'b', 'c', 'd'});

        Console.WriteLine (a==b);
        Console.WriteLine (a.Equals(b));

我的问题是何时应该使用==和何时应该使用等号?这两者有什么区别吗?


==是一个运算符,它在未重载时表示类的"引用相等"(和结构的字段相等),但可以重载。它是一个重载而不是重写的结果是它不是多态的。

equals是一个虚拟方法;这使它具有多态性,但意味着您需要注意不要在空实例上调用它。

根据经验:

  • 如果您知道某个东西的类型,并且知道它有一个==重载(大多数核心类型,如string、int、float等,都有==含义),那么使用==
  • 如果您不知道类型,建议使用等于(a,b)的值,因为这样可以避免出现空值问题。
  • 如果确实要检查同一实例(引用相等),请考虑使用reference equals(a,b),因为即使重载了==并重写了equals,这也会有效。
  • 在使用泛型时,考虑避免空问题、支持nullable-of-t、支持iequatable-of-t的EqualityComparer.Default.Equals(a,b)

约翰·斯基特的这篇文章将回答你的问题:

So, when should you use which operator? My rule of thumb is that for
almost all reference types, use Equals when you want to test equality
rather than reference identity. The exception is for strings -
comparing strings with == does make things an awful lot simpler and
more readable but you need to remember that both sides of the operator
must be expressions of type string in order to get the comparison to
work properly.

For value types, I'd normally use == for easier-to-read code. Things
would get tricky if a value type provided an overload for == which
acted differently to Equals, but I'd consider such a type very badly
designed to start with.

[Author: Jon Skeet]

http://blogs.msdn.com/b/csharpfaq/archive/2004/03/29/when-should-i-use-and-when-should-i-use-equals.aspx


When == is used on an object type, it'll resolve to
System.Object.ReferenceEquals.

Equals is just a virtual method and behaves as such, so the overridden
version will be used (which, for string type compares the contents).

https://stackoverflow.com/a/814880/655293