c 和等式運算子中的等式種類

在 C#中,有兩種不同的相等:引用相等和值相等。值相等是通常理解的相等含義:它意味著兩個物件包含相同的值。例如,值為 2 的兩個整數具有值相等性。引用相等意味著沒有兩個物件可供比較。相反,有兩個物件引用,它們都引用同一個物件。

object a = new object();
object b = a;
System.Object.ReferenceEquals(a, b);  //returns true

對於預定義的值型別,如果運算元的值相等,則相等運算子(==)返回 true,否則返回 false。對於除 string 之外的引用型別,如果其兩個運算元引用同一物件,則==返回 true。對於字串型別,==比較字串的值。

// Numeric equality: True
Console.WriteLine((2 + 2) == 4);

// Reference equality: different objects, 
// same boxed value: False.
object s = 1;
object t = 1;
Console.WriteLine(s == t);

// Define some strings:
string a = "hello";
string b = String.Copy(a);
string c = "hello";

// Compare string values of a constant and an instance: True
Console.WriteLine(a == b);

// Compare string references; 
// a is a constant but b is an instance: False.
Console.WriteLine((object)a == (object)b);

// Compare string references, both constants 
// have the same value, so string interning
// points to same reference: True.
Console.WriteLine((object)a == (object)c);