C# == 运算符详细做什么?

发布于 2024-07-19 10:55:29 字数 138 浏览 7 评论 0原文

在 C# 中,当您在两个对象上使用“==”运算符进行比较时,后台到底发生了什么? 它只是比较地址吗? 或者是类似 Equals() 或 CompareTo() 的东西吗?

PS:java中的“==”运算符怎么样? 它的行为相同吗?

in c# what does exactly happen in the background when you do a comparison with the "==" operator on two objects? does it just compare the addresses? or does it something like Equals() or CompareTo() ?

PS: what about the "==" operator in java? does it behave the same?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

紙鸢 2024-07-26 10:55:30

作为 Stefan 出色答案的扩展 -另一个例外是操作数涉及 Nullable - 在这种情况下适用“提升”运算符(ECMA 334v4 中的 14.2.7):

对于相等运算符
==!=

如果操作数类型都是,则存在运算符的提升形式
不可为 null 的值类型,并且如果
结果类型为bool。 抬起的形式
是通过添加单个 ? 来构造的
每个操作数类型的修饰符。 这
提升运算符考虑两个 null
值相等,空值不相等
任何非空值。 如果两者都
操作数非空,提升
运算符解开操作数并
将基础运算符应用于
产生布尔结果。

这意味着:因为(例如)之间存在一个相等运算符:

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

因此存在一个以下形式的隐式运算符(尽管做法不同):

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;
}

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):

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. 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.

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;
}
月牙弯弯 2024-07-26 10:55:30

来自 MSDN

对于预定义值类型,
相等运算符 (==) 返回 true,如果
其操作数的值相等,
否则为假。 对于参考类型
除了字符串之外,如果满足以下条件则 == 返回 true
它的两个操作数引用相同的
目的。 对于字符串类型,==
比较字符串的值。

From MSDN:

For predefined value types, the
equality operator (==) returns true if
the values of its operands are equal,
false otherwise. For reference types
other than string, == returns true if
its two operands refer to the same
object. For the string type, ==
compares the values of the strings.

拥抱影子 2024-07-26 10:55:30

不... == 运算符在 java 和 c# 中的行为并不总是相同。

例如字符串; Java == 确实比较字符串对象的引用...(如果使用原始类型,java 中的 == 会比较值)。 这就是为什么

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

在 java 中不会返回 true...

相比之下,在 C# 中, == 运算符在字符串上的行为确实有所不同。 例如,在以下情况下它将返回 true:

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

No ... the == operator does not always behave the same in java and in c#.

For example with Strings; Java == does compare the references of the string objects... (if you use primitve types, == in java compares the values). That's why

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

will not return true in java...

In C# in contrast, the == operator does behave different on strings. For example, it will return true in the following case:

// returns TRUE in C#
(new String("test".ToCharArray()) == "test") 
沫雨熙 2024-07-26 10:55:30

== 运算符的行为取决于您应用它的变量的声明方式(不是在对象的类上,我将添加一个示例)。

对于值类型,它将比较它们的值。

对于引用类型,如果 a 与 b 是同一对象,则 a == b 返回 true,除非 == 运算符被重载。 不像其他人所说的那样被重写,你不能重写 C# 中的运算符,因为它们不是虚拟的。

<代码>
对象 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();

该程序的输出是

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

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. Not overridden as others said, you can't override operators in c# because they are not virtual.


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

风吹雨成花 2024-07-26 10:55:29

据我所知:

  • 它按值(相等)比较值类型,
  • 它按引用(同一性)比较引用类型,
  • 除非 == 运算符重载,然后它会调用该运算符。

Equals 在对象中实现,也可以被覆盖。 Object 中的默认实现对引用类型执行引用比较。 所以默认情况下,Equals 和 == 的作用是相同的。

我认为在java中你不能重载==运算符。 但我的 Java 知识已经相当过时了。

编辑:
请注意,== 运算符是静态方法。 它在编译时根据变量或字段的类型进行绑定。 Equals 是一个在运行时根据实际运行时类型找到的虚拟方法。

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. The default implementation in Object performs a reference comparison for reference types. So by default, Equals and == do the same.

I think in java you cannot overload the == operator. But my Java knowledge is pretty outdated.

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文