# 相等运算符 - 测试两个对象是否相等

==（相等）!=（不等） 运算符检查其操作数是否相等。 当内容相等时，值类型相等。 当两个变量引用同一存储时，引用类型相等。

## 相等运算符 ==

### 值类型的相等性

int a = 1 + 2 + 3;
int b = 6;
Console.WriteLine(a == b);  // output: True

char c1 = 'a';
char c2 = 'A';
Console.WriteLine(c1 == c2);  // output: False
Console.WriteLine(c1 == char.ToLower(c2));  // output: True


==!= 运算符由 C# 元组支持。 有关详细信息，请参阅元组类型一文的元组相等部分。

### 引用类型的相等性

public class ReferenceTypesEquality
{
public class MyClass
{
private int id;

public MyClass(int id) => this.id = id;
}

public static void Main()
{
var a = new MyClass(1);
var b = new MyClass(1);
var c = a;
Console.WriteLine(a == b);  // output: False
Console.WriteLine(a == c);  // output: True
}
}


### 记录类型相等性

public class RecordTypesEquality
{
public record Point(int X, int Y, string Name);
public record TaggedNumber(int Number, List<string> Tags);

public static void Main()
{
var p1 = new Point(2, 3, "A");
var p2 = new Point(1, 3, "B");
var p3 = new Point(2, 3, "A");

Console.WriteLine(p1 == p2);  // output: False
Console.WriteLine(p1 == p3);  // output: True

var n1 = new TaggedNumber(2, new List<string>() { "A" });
var n2 = new TaggedNumber(2, new List<string>() { "A" });
Console.WriteLine(n1 == n2);  // output: False
}
}


### 字符串相等性

string s1 = "hello!";
string s2 = "HeLLo!";
Console.WriteLine(s1 == s2.ToLower());  // output: True

string s3 = "Hello!";
Console.WriteLine(s1 == s3);  // output: False


### 委托相等

Action a = () => Console.WriteLine("a");

Action b = a + a;
Action c = a + a;
Console.WriteLine(object.ReferenceEquals(b, c));  // output: False
Console.WriteLine(b == c);  // output: True


Action a = () => Console.WriteLine("a");
Action b = () => Console.WriteLine("a");

Console.WriteLine(a == b);  // output: False
Console.WriteLine(a + b == a + b);  // output: True
Console.WriteLine(b + a == a + b);  // output: False


## 不等运算符 !=

int a = 1 + 1 + 2 + 3;
int b = 6;
Console.WriteLine(a != b);  // output: True

string s1 = "Hello";
string s2 = "Hello";
Console.WriteLine(s1 != s2);  // output: False

object o1 = 1;
object o2 = 1;
Console.WriteLine(o1 != o2);  // output: True


## 运算符可重载性

public virtual bool Equals(T? other);