相等運算子 - 測試兩個物件相等或不相等

== (相等)!= (不等) 運算子可檢查其運算元是否相等。 實值型別在內容相等時相等。 兩個變數參考相同的儲存體時，參考型別會相等。

等號比較運算子 ==

實值型別相等

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# tuples 所支援。 如需詳細資訊，請參閱 Tuple 型別一文中的 Tuple 相等一節。

參考型別相等

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