C# difference between == and Equals()

前端 未结 17 1366
走了就别回头了
走了就别回头了 2020-11-21 06:56

I have a condition in a silverlight application that compares 2 strings, for some reason when I use == it returns false while .Equals()

17条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-21 07:52

    When comparing an object reference to a string (even if the object reference refers to a string), the special behavior of the == operator specific to the string class is ignored.

    Normally (when not dealing with strings, that is), Equals compares values, while == compares object references. If two objects you are comparing are referring to the same exact instance of an object, then both will return true, but if one has the same content and came from a different source (is a separate instance with the same data), only Equals will return true. However, as noted in the comments, string is a special case because it overrides the == operator so that when dealing purely with string references (and not object references), only the values are compared even if they are separate instances. The following code illustrates the subtle differences in behaviors:

    string s1 = "test";
    string s2 = "test";
    string s3 = "test1".Substring(0, 4);
    object s4 = s3;
    Console.WriteLine("{0} {1} {2}", object.ReferenceEquals(s1, s2), s1 == s2, s1.Equals(s2));
    Console.WriteLine("{0} {1} {2}", object.ReferenceEquals(s1, s3), s1 == s3, s1.Equals(s3));
    Console.WriteLine("{0} {1} {2}", object.ReferenceEquals(s1, s4), s1 == s4, s1.Equals(s4));
    

    The output is:

    True True True
    False True True
    False False True
    

提交回复
热议问题