C# Equals 和 ==

内容纲要

值类型 Equals 与 == 等同;
string 经过重写, Equals 与 == 等同;
object 类型,string 的特殊性;
其他类 类型。

            object t = "123";
            object a = t;
            object b = "123";
            Console.WriteLine(a == b);
            Console.ReadKey();
            object t = 1;
            object a = t;
            object b = 1;
            Console.WriteLine(a == b);
            Console.ReadKey();
            object t = 1;
            object a = t;
            object b = 1;
            Console.WriteLine(a.Equals(b));
            Console.ReadKey();

Equals 是比较是否同一对象,那么问题来了,有两种意思
是否是同一类型,还是说值相同

    public class Test
    {
        public int A { get; set; }
        public int B { get; set; }
    }
    class Program
    {
        static void Main()
        {
            Test a = new Test { A = 1, B = 2 };
            Test b = new Test { A = 2, B = 1 };
            Console.WriteLine(a.Equals(b));
            Console.ReadKey();
        }
    }

结果 False

    public class Test
    {
        public int A { get; set; }
        public int B { get; set; }
    }
    class Program
    {
        static void Main()
        {
            Test a = new Test { A = 1, B = 2 };
            Test b = new Test { A = 1, B = 2 };
            Console.WriteLine(a.Equals(b));
            Console.ReadKey();
        }
    }

Equpls 空引用会发生异常, == 不会。
Equals 与 == 区别,在于 null。

点赞
  1. quetiapine cost说道:

    I happen to be writing to make you understand what a wonderful experience our princess went through visiting yuor web blog. She realized too many things, with the inclusion of what it is like to possess an incredible teaching style to make the rest without problems understand various very confusing topics. You undoubtedly surpassed visitors' expected results. Thanks for supplying those warm and helpful, trustworthy, revealing not to mention unique tips on your topic to Tanya.

  2. I am glad for writing to make you know what a incredible encounter my friend's girl gained studying your web site. She learned plenty of pieces, which include what it's like to possess an awesome helping nature to let other folks very easily understand various very confusing topics. You undoubtedly surpassed visitors' expected results. Thanks for supplying those warm and friendly, trustworthy, revealing not to mention unique tips on your topic to Tanya.

发表评论

邮箱地址不会被公开。 必填项已用*标注

You must enable javascript to see captcha here!