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