標籤: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 本質理解