.Equals和= [duplicate]之间的区别是什么?

时间:2021-05-11 22:28:23

This question already has an answer here:

这个问题已经有了答案:

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.

对于值类型、引用类型和字符串,a = (b)和a == b有什么区别?似乎a == b对于字符串来说是可以的,但是我试图确保使用良好的编码实践。

9 个解决方案

#1


35  

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.

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

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.

对于没有重载的引用类型,它比较两个引用是否引用同一个对象——这正是Equals在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.

默认情况下,值类型不提供==的重载。然而,框架提供的大多数值类型提供了它们自己的重载。value类型的Equals的默认实现由ValueType提供,并使用反射进行比较,这使得它比特定类型的实现慢得多。这个实现还调用了两个值之间的对等引用。

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

#2


11  

Here is a great blog post about WHY the 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将在运行时被动态绑定。

#3


8  

In the most shorthand answer:

最简单的回答是:

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

= opertator就是检查一下身份。(我。e: a==b这两个是同一个物体吗?

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

. equals (), is to check value。(我。e: a = (b)的值是否相同?

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

除了一个例外:对于字符串和预定义值类型(如int、float等),运算符==将回答值而不是标识。(使用.Equals一样())

#4


7  

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.

在简单的层次上,区别在于调用哪个方法。方法将尝试将ot绑定到操作符== =,如果为所讨论的类型定义。如果对于值类型找到no =,它将进行值比较,对于引用类型,它将进行引用比较。. 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.

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

#5


7  

One significant difference between them is that == is a static binary operator that works on two instances of a type whereas Equals is 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);

#6


3  

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

一个简单的方法来帮助记住,a = (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()方法不是通用的,它接受“object”类型的参数,因此,当与==运算符进行比较时,您必须首先考虑它,就好像右边的操作数被转换为object。

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

其中一个含义是,无论类型是什么,a.Equals(b)几乎总是返回a和b的某个值(通常的重载方法是,如果b是未知类型,则返回false)。如果对这些类型没有可用的比较,a == b将抛出一个异常。

#7


0  

"==" 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 = (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.

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

#8


0  

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。比较(预期值,接受StringComparison ....)= = 0 ?使用您需要的StringComparison重载。

#9


0  

By default, both == and .Equals() are equivalent apart from the possibility of calling .Equals() on a null instance (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()外,都是等价的(这会给您一个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()而不是这两种方法中的任何一种。

#1


35  

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.

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

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.

对于没有重载的引用类型,它比较两个引用是否引用同一个对象——这正是Equals在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.

默认情况下,值类型不提供==的重载。然而,框架提供的大多数值类型提供了它们自己的重载。value类型的Equals的默认实现由ValueType提供,并使用反射进行比较,这使得它比特定类型的实现慢得多。这个实现还调用了两个值之间的对等引用。

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

#2


11  

Here is a great blog post about WHY the 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将在运行时被动态绑定。

#3


8  

In the most shorthand answer:

最简单的回答是:

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

= opertator就是检查一下身份。(我。e: a==b这两个是同一个物体吗?

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

. equals (), is to check value。(我。e: a = (b)的值是否相同?

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

除了一个例外:对于字符串和预定义值类型(如int、float等),运算符==将回答值而不是标识。(使用.Equals一样())

#4


7  

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.

在简单的层次上,区别在于调用哪个方法。方法将尝试将ot绑定到操作符== =,如果为所讨论的类型定义。如果对于值类型找到no =,它将进行值比较,对于引用类型,它将进行引用比较。. 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.

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

#5


7  

One significant difference between them is that == is a static binary operator that works on two instances of a type whereas Equals is 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);

#6


3  

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

一个简单的方法来帮助记住,a = (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()方法不是通用的,它接受“object”类型的参数,因此,当与==运算符进行比较时,您必须首先考虑它,就好像右边的操作数被转换为object。

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

其中一个含义是,无论类型是什么,a.Equals(b)几乎总是返回a和b的某个值(通常的重载方法是,如果b是未知类型,则返回false)。如果对这些类型没有可用的比较,a == b将抛出一个异常。

#7


0  

"==" 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 = (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.

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

#8


0  

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。比较(预期值,接受StringComparison ....)= = 0 ?使用您需要的StringComparison重载。

#9


0  

By default, both == and .Equals() are equivalent apart from the possibility of calling .Equals() on a null instance (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()外,都是等价的(这会给您一个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()而不是这两种方法中的任何一种。