C#實現相等性判斷的方法:
//確定指定的 System.Object 是否等於當前的 System.Object
public virtual bool Equals(object obj) { return RuntimeHelpers.Equals(this, obj); } //確定是否將指定的 System.Object 實例視為相等 public static bool Equals(object objA, object objB) { return ((objA == objB) || (((objA != null) && (objB != null)) && objA.Equals(objB))); } //確定指定的 System.Object 實例是否是相同的實例 public static bool ReferenceEquals(object objA, object objB) { return (objA == objB); }
== 和 !=運算符比較內容
**********************************************************************************************************************
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; namespace ValueTypeDemo { //鞋子類 class Shoes { private string name; //品名 private int price; //單價 public string Name { get { return name; } set { name = value; } } public int Price { get { return price; } set { price = value; } } } class Program { static void Main(string[] args) { Shoes S1 = new Shoes(); Shoes S2 = new Shoes(); Shoes S3 = S2; int x = 5; int y = 8; int z = x; object A = 11; object B = A; object C = 11; //內容比較 Console.WriteLine(x==y); //false Console.WriteLine(x==z); //true //裝箱後按引用比較 Console.WriteLine(A==B); //true Console.WriteLine(A==C); //false //裝箱後按裝箱前類型比較值是否相等 Console.WriteLine(A.Equals(B)); //true Console.WriteLine(A.Equals(C)); //true Console.WriteLine(Equals(A, B)); //true Console.WriteLine(Equals(A, C)); //true //強制按引用比較 Console.WriteLine(ReferenceEquals(A,B)); //true Console.WriteLine(ReferenceEquals(A,C)); //false Console.ReadKey(); } } }