你的位置:首页 > ASP.net教程

[ASP.net教程]C#之相等性判断探秘

  C#实现相等性判断的方法:

  1. public virtual bool Equals(object obj);
  2. public static bool Equals(object objA, object objB);
  3. public static bool ReferenceEquals(object objA, object objB);
  4. “==”运算符
//确定指定的 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();    }  }}