CSharp four kinds of forms equal Analyzing

      The C # language, there is determined for an equal variables in the form of four, two static methods of the object class: ReferenceEquals (obj1, boj2) and Equals (obj1, obj2), as well as examples of methods Equals (), and heavy-duty operation symbol ==.

      (1) ReferenceEquals, see the name to know it is to compare two variables of reference type, so it is clear that two types of values ​​will always return false, even if it is compared to the value of the type variable itself, also returns false (it comes to packing);

      (2) static Equals, decompile dll can see the actual call Equals method is an instance method Equals first variable, so its return value depends on the type of the variable Equals method.

      (3) The method of Example Equals default comparison is "equal to a reference." But for System.ValueType overrides this method, the value type is no longer press the "reference equality" to compare. For value type, the best method override Equals; System.String The class also rewrite Equals, so two will return the same string content True.

      (4) == operator overloading, the same method Equals instance, the default is to compare "reference equality", but also String ValueType and rewriting were made.

     In the console project tested as follows:

 static void Main(string[] args)
        {
            int i = 1;
            int j = 1;

            myData md1 = new myData("aaa");
            myData md2 = new myData("bbb");
            myData md3 = md1;

            //test referenceEquals
            Console.WriteLine(object.ReferenceEquals(i, j));
            Console.WriteLine(object.ReferenceEquals(i, i));
            Console.WriteLine(object.ReferenceEquals(md1, md2));
            Console.WriteLine(object.ReferenceEquals(md1, md3));

            //test static Equals
            Console.WriteLine(object.Equals(i, j));
            Console.WriteLine(object.Equals(md1, md2));
            Console.WriteLine(object.Equals(md1, md3));

            //test Equals
            Console.WriteLine(i.Equals(j));
            Console.WriteLine(md1.Equals(md3));

            //test ==
            Console.WriteLine(i == j);
            Console.WriteLine(md1 == md3);
        }

 public class myData
    {
        string _str = string.Empty;

        public myData(string str)
        {
            _str = str;
        }
    }

Results are as follows:

 

 

 

Reproduced in: https: //www.cnblogs.com/JasonCrab/archive/2009/06/23/1508766.html

Guess you like

Origin blog.csdn.net/weixin_34404393/article/details/94278729