C# == equals 本质理解

using System;
using System.Diagnostics;
using System.Text;
using System.Collections;
using System.Collections.Generic;

class Test
{
    static void print(object obj)
    {
        Console.WriteLine(obj);
    }
    class CDefOveride //C# 的所有类都默认继承于object,这里不用写继承,也可以写,有点诡异
    {
        public override bool Equals(object obj)//重写object.Equals(object obj),系统的string类也是这么做的
        {
            print("cdefoveride.equals");
            return true;
        }
    }
    static void Main()
    {
        string sa = new string(new char[] { 'h', 'e', 'l', 'l', 'o' });
        string sb = new string(new char[] { 'h', 'e', 'l', 'l', 'o' });

        print(sa.GetHashCode() + "," + sb.GetHashCode());
        print(sa.Equals(sb));//true,调用string.equals(string)
        print(sa == sb);//true,string的operator ==
        object oa = sa;
        object ob = sb;
        print(oa.Equals(ob));//true, 多态调用,实际调用的是string.Equals(object)
        print(oa == ob); //false

        object oc = new object();
        object od = new object();
        print(oc.Equals(od)); //false, object.equals(object)
        print(oc == od);//false
        //如果没有实现重写,对于引用类型,那么原始的object.equals()与 ==没有任何区别,二者总能得到一样的结果
        //因为引用类型其实是一个指针,==比较的是指针的值,也就是地址,equals比较的也是地址。
        //string类重写了==和equals,实现了字符串内容的比较,而非地址的比较。

        object o1 = new CDefOveride();
        object o2 = new CDefOveride();

        print(o1.Equals(o2)); //false, 多态调用, CDefOveride.Equals(object)

        int ia = 12;
        short isa = 12;
        print(ia.Equals(isa)); // true, short可以转为int,故多态调用Int32.Equals(Int32 obj)
        print(isa.Equals(ia)); // false, int不能直接转为short,故多态调用Int16.Equals(object obj)
    }

}
原文地址:https://www.cnblogs.com/timeObjserver/p/6032084.html