Difference between Equals/equals and == operator?

前端 未结 11 953
一生所求
一生所求 2020-11-22 14:14

What is the difference between a == b and a.Equals(b)?

11条回答
  •  春和景丽
    2020-11-22 14:52

    String a = "toto".Substring(0, 4);
    String b = "toto";
    Object aAsObj = a;
    Assert.IsTrue(a.Equals(b));
    Assert.IsTrue(a == b);
    Assert.IsFalse(aAsObj == b);
    Assert.IsTrue(aAsObj.Equals(b));
    

    This test pass in .NET, the trick is that Equals is a method, whereas == is a static method, so aAsObj == b use

    static bool Object.operator==(object a, object b) //Reference comparison
    

    whereas a == b use

    static bool String.operator==(string a, string b) //String comparison
    

    but a.Equals(b) or aAsObj.Equals(b) always use :

    bool String.Equals(Object obj) //String comparison
    

提交回复
热议问题