C# .Equals 和 == 有什么区别

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/772953/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-05 00:34:41  来源:igfitidea点击:

What is the difference between .Equals and ==

c#.netstring

提问by CodeMonkey1313

What is the difference between a.Equals(b)and a == bfor 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.

是什么区别a.Equals(b)a == b值类型,引用类型和字符串?似乎 a == b 对字符串工作得很好,但我正在努力确保使用良好的编码实践。

采纳答案by Dirk Vollmar

From When should I use Equals and when should I use ==:

什么时候应该使用Equals和何时应使用==

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.

Equals 方法只是在 System.Object 中定义的一个虚拟方法,并被任何选择这样做的类覆盖。== 运算符是一个可以被类重载的运算符,但它通常具有标识行为。

对于 == 没有被重载的引用类型,它比较两个引用是否引用同一个对象——这正是 System.Object 中 Equals 的实现所做的。

默认情况下,值类型不为 == 提供重载。但是,框架提供的大多数值类型都提供了它们自己的重载。值类型的 Equals 的默认实现由 ValueType 提供,并使用反射进行比较,这使得它比通常的类型特定实现慢得多。此实现还对要比较的两个值中的引用对调用 Equals。

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

回答by Josh G

"==" is an operator that can be overloaded to perform different things based on the types being compared.

" ==" 是一个运算符,可以根据要比较的类型进行重载以执行不同的操作。

The default operation performed by "==" is a.Equals(b);

" =="执行的默认操作是a.Equals(b);

Here's how you could overload this operator for string types:

以下是为字符串类型重载此运算符的方法:

public static bool operator == (string str1, string str2) 
{
    return (str1.Length == str2.Length;)
}

Note that this is different than str1.Equals(str2);

请注意,这与 str1.Equals(str2);

Derived classes can also override and redefine Equals().

派生类也可以覆盖和重新定义Equals()

As far as "best practices" go, it depends on your intent.

就“最佳实践”而言,这取决于您的意图。

回答by JaredPar

At a simple level, the difference is which method is called. The == method will attempt ot bind to operator== if defined for the types in question. If no == is found for value types it will do a value comparison and for reference types it will do a reference comparison. A .Equals call will do a virtual dispatch on the .Equals method.

简单来说,区别在于调用的是哪个方法。如果为相关类型定义, == 方法将尝试绑定到 operator== 。如果没有找到值类型的 ==,它将进行值比较,而对于引用类型,它将进行引用比较。.Equals 调用将对 .Equals 方法进行虚拟调度。

As to what the particular methods do, it's all in the code. Users can define / override these methods and do anything they please. Ideally this methods should be equivalent (sorry for the pun) and have the same output but it is not always the case.

至于具体的方法做什么,全都在代码中。用户可以定义/覆盖这些方法并做任何他们想做的事情。理想情况下,这种方法应该是等效的(抱歉双关语)并且具有相同的输出,但情况并非总是如此。

回答by Andrew Hare

One significant difference between them is that ==is a static binary operator that works on two instances of a type whereas Equalsis an instance method. The reason this matters is that you can do this:

它们之间的一个显着区别==是静态二元运算符适用于一个类型的两个实例,而Equals是一个实例方法。这很重要的原因是你可以这样做:

Foo foo = new Foo()
Foo foo2 = null;
foo2 == foo;

But you cannot do this without throwing a NullReferenceException:

但是你不能不抛出一个NullReferenceException

Foo foo = new Foo()
Foo foo2 = null;
foo2.Equals(foo);

回答by Quibblesome

For strings you want to be careful of culture specific comparisons. The classic example is the german double S, that looks a bit like a b. This should match with "ss" but doesn't in a simple == comparison.

对于字符串,您需要注意特定于文化的比较。经典的例子是德式双 S,看起来有点像 b。这应该与“ss”匹配,但不是简单的 == 比较。

For string comparisons that are culture sensitive use: String.Compare(expected, value, StringComparison....) == 0 ? with the StringComparison overload you need.

对于区分区域性的字符串比较,请使用: String.Compare(expected, value, StringComparison....) == 0 ? 使用您需要的 StringComparison 重载。

回答by Adam Robinson

By default, both ==and .Equals()are equivalent apart from the possibility of calling .Equals()on a nullinstance (which would give you a NullReferenceException). You can, however, override the functionality of either of them independently (though I'm not sure that would ever be a good idea unless you're trying to work around the shortcomings of another system), which would mean you could MAKE them different.

默认情况下,==.Equals()等价除了呼吁的可能性.Equals()上一个null实例(会给你一个NullReferenceException)。但是,您可以独立地覆盖其中任何一个的功能(尽管我不确定这是否是一个好主意,除非您试图解决另一个系统的缺点),这意味着您可以使它们与众不同.

You'll find people on both sides of the aisle as to the one to use. I prefer the operator rather than the function.

您会在过道的两侧找到要使用的人。我更喜欢运算符而不是函数。

If you're talking about strings, though, it's likely a better idea to use string.Compare()instead of either one of those options.

但是,如果您在谈论字符串,那么使用string.Compare()这些选项中的任何一个来代替可能是一个更好的主意。

回答by Chris Shaffer

Here is a great blog post about WHYthe implementations are different.

这是一篇关于为什么实现不同的很棒的博客文章

Essentially == is going to be bound at compile time using the types of the variables and .Equals is going to be dynamically bound at runtime.

本质上 == 将在编译时使用变量的类型进行绑定,而 .Equals 将在运行时动态绑定。

回答by Joel Coehoorn

One simple way to help remember the difference is that a.Equals(b)is more analogous to
a == (object)b.

帮助记住差异的一种简单方法a.Equals(b)是更类似于
a == (object)b.

The .Equals()method is not generic and accepts an argument of type "object", and so when comparing to the == operator you have to think about it as if the right-hand operand were cast to object first.

.Equals()方法不是通用的,并且接受“对象”类型的参数,因此在与 == 运算符进行比较时,您必须将其视为首先将右侧操作数强制转换为对象。

One implication is that a.Equals(b)will nearly always return some value for aand b, regardless of type (the normal way to overload is to just return falseif bis an unkown type). a == bwill just throw an exception if there's no comparison available for those types.

一个含义是a.Equals(b)几乎总是为aand返回一些值,而b不管类型如何(重载的正常方法是只返回falseifb是未知类型)。 a == b如果这些类型没有可用的比较,则只会抛出异常。

回答by G.Y

In the most shorthand answer:

最简略的回答:

== opertator is to check identity.(i.e: a==b are these two are the same object?)

== operator 是检查身份。(即:a==b 这两个是同一个对象吗?)

.Equals() is to check value.(i.e: a.Equals(b) are both holding identical values?)

.Equals() 是检查值。(即:a.Equals(b) 都持有相同的值?)

With one exception:
For stringand predefined value types(such as int, floatetc..),
the operator == will answer for value and not identity. (same as using .Equals())

有一个例外:
对于字符串预定义的值类型(例如intfloat等),
运算符 == 将回答值而不是身份。(与使用 .Equals() 相同)