Equals与==操作符

==操作符

1.对于值类型,比较对象的值。
2. 对于string 以外的引用类型,比较两个对象的地址。
3. 对于 string 类型,比较字符串的值。

Object.Equals

  1. 对于值类型,比较对象的值。
  2. 对于引用类型,比较是否是对同一个对象的引用。

MSDN的说明:

https://msdn.microsoft.com/zh-cn/library/bsc2ak47(v=vs.110).aspx

using System;

// Define a reference type that does not override Equals.
public class Person
{
   private string personName;

   public Person(string name)
   {
      this.personName = name;
   }

   public override string ToString()
   {
      return this.personName;
   }
}

public class Example
{
   public static void Main()
   {
      Person person1a = new Person("John");
      Person person1b = person1a;
      Person person2 = new Person(person1a.ToString());

      Console.WriteLine("Calling Equals:"); 
      Console.WriteLine("person1a and person1b: {0}", person1a.Equals(person1b));               
      Console.WriteLine("person1a and person2: {0}", person1a.Equals(person2));  

      Console.WriteLine("\nCasting to an Object and calling Equals:");
      Console.WriteLine("person1a and person1b: {0}", ((object) person1a).Equals((object) person1b));
      Console.WriteLine("person1a and person2: {0}", ((object) person1a).Equals((object) person2)); 
   }
}
// The example displays the following output:
//       person1a and person1b: True
//       person1a and person2: False
//       
//       Casting to an Object and calling Equals:
//       person1a and person1b: True
//       person1a and person2: False

你可能感兴趣的:(C#语法)