对象平等在.NET中表现不同平等、对象、不同、NET

2023-09-04 00:19:56 作者:无法忘却的旧爱

我有这些语句和他们'的结果是接近他们。

 字符串=ABC;
字符串B =ABC;

Console.Writeline(A == B); //真正

对象x =一个;
对象计算y = b;

Console.Writeline(x == y)的; // 真正

串c =新的字符串(新的char [] {A,B,C});
串D =新的字符串(新的char [] {A,B,C});

Console.Writeline(C = D); // 真正

对象K =℃;
物体M = D;

Console.Writeline(k.Equals(M))//真

Console.Writeline(K = = M); // 假
 

为什么最后一个等式给了我假?

现在的问题是,为什么(x == y)为真(K = = M)是假的。

解决方案

 字符串=ABC;
字符串B =ABC;

Console.Writeline(A == B); //真正
 

字符串引用是相同的相同的字符串因的字符串实习的

 对象x = A;
对象计算y = b;

Console.Writeline(x == y)的; // 真正
 
机遇不平等 概念 机制与启示

由于引用来自相同的参考创建的相同,两个对象也相同。

 串c =新的字符串(新的char [] {A,B,C});
串D =新的字符串(新的char [] {A,B,C});
 

在这里,你创建人物的两个新的数组,这些引用是不同的。

  Console.Writeline(C = D); // 真正
 

字符串重载==按值进行比较。

 对象K =℃;
物体M = D;
 

由于previous引用是不同的,这些对象是不同的。

  Console.Writeline(k.Equals(M))//真
 

.Equals 使用重载字符串等于方法,再由值进行比较

  Console.Writeline(K = = M); // 假
 

在这里,我们检查是否两个引用是相同的,就不是

关键是搞清楚当平等是比较引用或值。

对象,除非另有超载,比较引用

结构体,除非另有超负荷,比较值。

I have these statements and their' results are near them.

string a = "abc";
string b = "abc";

Console.Writeline(a == b); //true

object x = a;
object y = b;

Console.Writeline(x == y); // true

string c = new string(new char[] {'a','b','c'});
string d = new string(new char[] {'a','b','c'});

Console.Writeline(c == d); // true

object k = c;
object m = d;

Console.Writeline(k.Equals(m)) //true

Console.Writeline(k == m); // false

Why the last equality gives me false ?

The question is why ( x == y ) is true ( k == m ) is false

解决方案

string a = "abc"; 
string b = "abc"; 

Console.Writeline(a == b); //true 

String references are the same for the same string due to String Interning

object x = a; 
object y = b; 

Console.Writeline(x == y); // true 

Because the references are the same, two objects created from the same reference are also the same.

string c = new string(new char[] {'a','b','c'}); 
string d = new string(new char[] {'a','b','c'}); 

Here you create two NEW arrays of characters, these references are different.

Console.Writeline(c == d); // true 

Strings have overloaded == to compare by value.

object k = c; 
object m = d; 

Since the previous references are different, these objects are different.

Console.Writeline(k.Equals(m)) //true 

.Equals uses the overloaded String equals method, which again compare by value

Console.Writeline(k == m); // false 

Here we check to see if the two references are the same... they are not

The key is figuring out when an equality is comparing references or values.

Objects, unless otherwise overloaded, compare references.

Structs, unless otherwise overloaded, compare values.