日期:2014-05-17  浏览次数:21044 次

C#相等比较用法总结

C#中提供了4种相等比较的方法,现将这4种相等比较的用法总结如下。

public class Student
{
     private string name;
     public Student(string name)
     {
          this.name = name;
     }

     public void ShowName()
     {
         Console.WriteLine(this.name );
     }
}

static void Main(string[] args)
{
      string daShuai="DaShuai";
      string baWang="DaShuai";

      int daShuaiAge = 25;        
      int baWangAge = 25;

      Student DaShuai, BaWang;
      DaShuai = new Student(daShuai);
      BaWang = new Student(baWang);

      //1.实例Equals()方法
      bool b1 = daShuai.Equals(baWang);
      bool b2 = daShuaiAge.Equals(baWangAge);
      bool b3 = DaShuai.Equals(BaWang);

      Console.WriteLine("1.Equals");
      Console.WriteLine("daShuai.Equals(baWang):{0}",b1);
      Console.WriteLine("daShuaiAge.Equals(baWangAge):{0}", b2);
      Console.WriteLine("DaShuai.Equals(BaWang):{0}", b3);

      Console.WriteLine("~~~~~~~~~~>_<~~~~~~~~~~");

      //2.= =
      bool b4 = daShuai == baWang;
      bool b5 = daShuaiAge == baWangAge;
      bool b6 = DaShuai == BaWang;

      Console.WriteLine("2.==");
      Console.WriteLine("daShuai == baWang:{0}", b4);
      Console.WriteLine("daShuaiAge == baWangAge:{0}", b5);
      Console.WriteLine("DaShuai == BaWang:{0}", b6);

      Console.WriteLine("~~~~~~~~~~>_<~~~~~~~~~~");

      //3.ReferenceEquals()方法
      bool b7 = ReferenceEquals(daShuai, baWang);
      bool b8 = ReferenceEquals(daShuaiAge, baWangAge);
      bool b9 = ReferenceEquals(DaShuai, BaWang);

      Console.WriteLine("3.ReferenceEquals");
      Console.WriteLine("ReferenceEquals(daShuai, baWang):{0}", b7);
      Console.WriteLine("ReferenceEquals(daShuaiAge, baWangAge):{0}", b8);
      Console.WriteLine("ReferenceEquals(DaShuai, BaWang):{0}", b9);

      Console.WriteLine("~~~~~~~~~~>_<~~~~~~~~~~");

      //4.静态的Equals()方法
      bool b10 = Equals(daShuai, baWang);
      bool b11 = Equals(daShuaiAge, baWangAge);
      bool b12 = Equals(DaShuai, BaWang);

      Console.WriteLine("4.静态的Equals");
      Console.WriteLine("Equals(daShuai, baWang):{0}", b10);
      Console.WriteLine("Equals(daShuaiAge, baWangAge):{0}", b11);
      Console.WriteLine("Equals(DaShuai, BaWang):{0}", b12);
}

运行程序,结果如下:

结果分析:

实例中分别使用Equals()方法, = =运算符,ReferenceEquals()方法,静态的Equals()方法对字符串,整型数据,引用类型数据进行相等比较操作。

1.实例Equals()方法

对于字符串:

String