码迷,mamicode.com
首页 > Windows程序 > 详细

C# == equals 本质理解

时间:2016-11-05 02:40:11      阅读:177      评论:0      收藏:0      [点我收藏+]

标签: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 本质理解

标签:class   多态   ide   err   test   equals   eth   类型   turn   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!