C#中==和equals的区别

来源:互联网 发布:阿里短信平台 php 编辑:程序博客网 时间:2024/05/18 03:25
 写个控制台程序跑了一下 

        public class persons
        {
            public string name;
        }


        static void Main(string[] args)
        {
            //字符串 特殊的引用类型==就是比较内容是否一致 equals也是查看值是否相等
            //string str1 = new string(new char[] { 'h', 'e', 'l', 'l', 'o' });
            string str2 = new string(new char[] { 'h', 'e', 'l', 'l', 'o' });
            string str1 = "hello";
            //string str2 = "hello";
            Console.WriteLine("字符串 特殊的引用类型==就是比较内容是否一致 equals也是查看值是否相等");
            Console.WriteLine(str1 == str2);//true
            Console.WriteLine(str2.Equals(str1));//true


            //引用类型 ==就是比较引用是否一样 引用类型equals默认也是比较引用是否一样
            persons p1 = new persons();
            p1.name = "11111";
            object obj100 = p1;
            persons p2 = new persons();
            p2.name = "11111";
            object obj200 = p2;
            Console.WriteLine("引用类型 ==就是比较引用是否一样 equals也是比较引用是否一样");
            Console.WriteLine(p1 == p2);//false
            Console.WriteLine(p1.Equals(p2));//false 内容是一样的,但是输出的还是false和书本上以及网络中的描述不一致 引用类型的equals默认还是比较的地址,如果想比较内容就要重写equals方法
            Console.WriteLine(obj100.Equals(obj200));
            Console.WriteLine(obj100.ToString()==obj200.ToString());


            //值类型 都是比较数值是否相等
            int i1 = 100;
            int i2 = 100;
            Console.WriteLine("值类型 都是比较数值是否相等");
            Console.WriteLine(i1 == i2);//true
            Console.WriteLine(i1.Equals(i2));//true   


            string a = "hello";
            string b = "hello";
            object g = a;
            object h = b;
            Console.WriteLine(g == h);//true
            Console.WriteLine(g.Equals(h));//true


            string a1 = new string(new char[] { 'h', 'e', 'l', 'l', 'o' });
            string b1 = "hello";
            //装箱之后==就不一样了,equals还是一样的
            object g1 = a1;
            object h1 = b1;
            Console.WriteLine(g1 == h1);//false
            Console.WriteLine(g1.Equals(h1));//true   
            Console.ReadLine();
        }

           

原创粉丝点击