C# == equals 本质理解
生活随笔
收集整理的這篇文章主要介紹了
C# == equals 本质理解
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
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); //falseobject 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) }}?
posted on 2016-11-04 23:21 時空觀察者9號 閱讀(...) 評論(...) 編輯 收藏
總結
以上是生活随笔為你收集整理的C# == equals 本质理解的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: C++函数内存占用
- 下一篇: U3D 扩展方法 Dotween t