C# == equals 本質理解

來源:互聯網
上載者:User

標籤:class   多態   ide   err   test   equals   eth   類型   turn   

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)    }}

 

C# == equals 本質理解

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.