对比C#中==与equal方法

C#中equal与==的区别 收藏 
对于值类型,如果对象的值相等,则相等运算符 (==) 返回 true,否则返回 false。对于string 以外的引用类型,如果两个对象引用同一个对象,则 == 返回 true。对于 string 类型,== 比较字符串的值。
==操作比较的是两个变量的值是否相等。
equals()方法比较的是两个对象的内容是否一致.==也就是比较引用类型是否是对同一个对象的引用。

例子:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string a = new string(new char[] { 'h', 'e', 'l', 'l', 'o' });
            string b = new string(new char[] { 'h', 'e', 'l', 'l', 'o' });
            Console.WriteLine(a == b);
            Console.WriteLine(a.Equals(b));

            object g = a;
            object h = b;
            Console.WriteLine(g == h);
            Console.WriteLine(g.Equals(h));

            Person p1 = new Person("jia");
            Person p2 = new Person("jia");
            Console.WriteLine(p1 == p2);
            Console.WriteLine(p1.Equals(p2));


            Person p3 = new Person("jia");
            Person p4 = p3;
            Console.WriteLine(p3 == p4);
            Console.WriteLine(p3.Equals(p4));

            Console.ReadLine();
        }
    }
}


输出
true,true,false,true,false,false,true,true。