简体   繁体   English

C#==运算符详细说明了什么?

[英]C# what does the == operator do in detail?

in c# what does exactly happen in the background when you do a comparison with the "==" operator on two objects? 在c#中,当你在两个对象上与“==”运算符进行比较时,后台究竟发生了什么? does it just compare the addresses? 它只是比较地址? or does it something like Equals() or CompareTo() ? 或者像Equals()或CompareTo()这样的东西?

PS: what about the "==" operator in java? PS:java中的“==”运算符怎么样? does it behave the same? 它的行为是否相同?

As far as I know: 我所知道的:

  • it compares value types by value (equality) 它按值比较值类型(相等)
  • it compares reference types by reference (identity) 它通过引用比较引用类型(标识)
  • except if the == operator is overloaded, then it calls that one. 除非==运算符被重载,否则它会调用那个。

Equals is implemented in object and can be overridden as well. Equals在object中实现,也可以被覆盖。 The default implementation in Object performs a reference comparison for reference types. Object中的默认实现执行引用类型的引用比较。 So by default, Equals and == do the same. 所以默认情况下,Equals和==也是这样。

I think in java you cannot overload the == operator. 我认为在java中你不能重载==运算符。 But my Java knowledge is pretty outdated. 但我的Java知识已经过时了。

Edit: Note that the == operator is a static method. 编辑:请注意, ==运算符是静态方法。 It is bound at compile time, base on the types of your variables or fields. 它在编译时绑定,基于变量或字段的类型。 Equals is a virtual method that is found at runtime, based on actual runtime types. Equals是一种基于实际运行时类型在运行时找到的虚方法。

As an extension to Stefan's excellent answer - another exception is if the operands involve Nullable<T> - in which case "lifted" operators apply (14.2.7 in ECMA 334v4): 作为Stefan优秀答案的延伸 - 另一个例外是操作数涉及Nullable<T> - 在这种情况下“提升”运算符适用(ECMA 334v4中为14.2.7):

For the equality operators == != 对于相等运算符==!=

a lifted form of an operator exists if the operand types are both non-nullable value types and if the result type is bool. 如果操作数类型都是非可空值类型并且结果类型是bool,则存在提升形式的运算符。 The lifted form is constructed by adding a single ? 提升形式是通过添加一个? modifier to each operand type. 每个操作数类型的修饰符。 The lifted operator considers two null values equal, and a null value unequal to any non-null value. 提升的运算符认为两个空值相等,并且空值不等于任何非空值。 If both operands are non-null, the lifted operator unwraps the operands and applies the underlying operator to produce the bool result. 如果两个操作数都为非null,则提升的运算符将解包操作数并应用基础运算符以生成bool结果。

What that means is: because there is an equality operator between (say): 这意味着:因为(例如)之间有一个相等运算符:

int i = ..., j = ...;
bool eq = i == j;

Thus there is an implicit operator of the form (although done differently): 因此,有一个表单的隐式运算符(尽管做得不同):

int? i = ..., j = ...;
bool eq;
if(i.HasValue) {
    if(j.HasValue) { // both have values; compare
       eq = i.GetValueOrDefault() == j.GetValueOrDefault();
    } else { // one null; always false
       eq = false;
    }
} else { // true if both null, else false
    eq = !j.HasValue;
}

From MSDN : 来自MSDN

For predefined value types, the equality operator (==) returns true if the values of its operands are equal, false otherwise. 对于预定义的值类型,如果操作数的值相等,则相等运算符(==)返回true,否则返回false。 For reference types other than string, == returns true if its two operands refer to the same object. 对于除string之外的引用类型,如果其两个操作数引用同一对象,则==返回true。 For the string type, == compares the values of the strings. 对于字符串类型,==比较字符串的值。

No ... the == operator does not always behave the same in java and in c#. 否...... ==运算符在java和c#中的行为并不总是相同。

For example with Strings; 例如使用Strings; Java == does compare the references of the string objects... (if you use primitve types, == in java compares the values). Java ==会比较字符串对象的引用...(如果使用primitve类型,则在java中使用==比较值)。 That's why 这就是为什么

// returns FALSE in JAVA
(new String("test") == "test") 

will not return true in java... 在java中不会返回true ...

In C# in contrast, the == operator does behave different on strings. 相反,在C#中,==运算符在字符串上的行为不同。 For example, it will return true in the following case: 例如,在以下情况下它将返回true:

// returns TRUE in C#
(new String("test".ToCharArray()) == "test") 

The behavior of == operator depends how the variable you are applying it to was declared (not on the class of the object, I'll add an example). ==运算符的行为取决于您应用它的变量是如何声明的(不是在对象的类上,我将添加一个示例)。

For value types it will compare their values. 对于值类型,它将比较它们的值。

For reference types a == b returns true if a is the same object as b, unless the == operator was overloaded. 对于引用类型,如果a与b是同一个对象,则a == b将返回true,除非==运算符被重载。 Not overridden as others said, you can't override operators in c# because they are not virtual. 没有像其他人所说的那样被覆盖,你不能覆盖c#中的运算符,因为它们不是虚拟的。

object obj_a, obj_b; string str_a, str_b;

  str_a = "ABC"; str_b = new string("ABC".ToCharArray()); obj_a = str_a; obj_b = str_b; Console.WriteLine("str_a == str_b = {0}", str_a == str_b); // in string == operator is overloaded Console.WriteLine("str_a.Equals(str_b) = {0}", str_a.Equals(str_b)); // string overrides Object.Euqals Console.WriteLine("obj_a == obj_b = {0}", obj_a == obj_b); // in object == operator is not overloaded Console.WriteLine("obj_a.Equals(obj_b) = {0}", obj_a.Equals(obj_b)); // Object.Equesl is virtual and overridden method from string will be executed. Console.ReadKey(); 

The output of that program is 该计划的输出是

str_a == str_b = True
str_a.Equals(str_b) = True
obj_a == obj_b = False
obj_a.Equals(obj_b) = True

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM