本文翻译自:Why would you use String.Equals over ==? [duplicate]
This question already has an answer here: 这个问题已经在这里有了答案:
C# difference between == and Equals() 17 answers ==和Equals()之间的C#差异 17个答案I recently was introduced to a large codebase and noticed all string comparisons are done using String.Equals() instead of == 我最近被介绍给大型代码库,并注意到所有字符串比较都是使用String.Equals()而不是==
What's the reason for this, do you think? 您认为这是什么原因?
参考:https://stackoom.com/question/6xbd/为什么要使用String-Equals-over-重复
Both methods do the same functionally - they compare values . 两种方法的功能相同-比较值 。 As is written on MSDN: 正如在MSDN上所写:
About String.Equals method - Determines whether this instance and another specified String object have the same value. 关于String.Equals方法-确定此实例和另一个指定的String对象是否具有相同的值。 ( http://msdn.microsoft.com/en-us/library/858x0yyx.aspx ) ( http://msdn.microsoft.com/en-us/library/858x0yyx.aspx ) About == - Although string is a reference type, the equality operators ( == and != ) are defined to compare the values of string objects, not references. 关于== -尽管string是引用类型,但定义了相等运算符( ==和!= )来比较字符串对象(而不是引用)的值。 This makes testing for string equality more intuitive. 这使得测试字符串相等性更加直观。 ( http://msdn.microsoft.com/en-en/library/362314fe.aspx ) ( http://msdn.microsoft.com/zh-cn/library/362314fe.aspx )But if one of your string instances is null, these methods are working differently: 但是,如果您的字符串实例之一为null,则这些方法的工作方式有所不同:
string x = null; string y = "qq"; if (x == y) // returns false MessageBox.Show("true"); else MessageBox.Show("false"); if (x.Equals(y)) // returns System.NullReferenceException: Object reference not set to an instance of an object. - because x is null !!! MessageBox.Show("true"); else MessageBox.Show("false");I've just been banging my head against a wall trying to solve a bug because I read this page and concluded there was no meaningful difference when in practice there is so I'll post this link here in case anyone else finds they get different results out of == and equals. 我一直在试图解决一个错误,这是因为我读了本页,并得出结论,在实践中并没有什么实质性的区别,所以我将在此发布此链接,以防其他人发现他们得到不同的结果等于=且等于。
Object == equality fails, but .Equals succeeds. 对象==相等失败,但是.Equals成功。 Does this make sense? 这有意义吗?
string a = "x"; string b = new String(new []{'x'}); Console.WriteLine("x == x " + (a == b));//True Console.WriteLine("object x == x " + ((object)a == (object)b));//False Console.WriteLine("x equals x " + (a.Equals(b)));//True Console.WriteLine("object x equals x " + (((object)a).Equals((object)b)));//TrueI want to add that there is another difference. 我想补充一点,还有另一个区别。 It is related to what Andrew posts. 这与安德鲁发布的内容有关。
It is also related to a VERY annoying to find bug in our software. 这也与非常烦人的在我们的软件中发现错误有关。 See the following simplified example (I also omitted the null check). 请参见下面的简化示例(我也省略了null检查)。
public const int SPECIAL_NUMBER = 213; public bool IsSpecialNumberEntered(string numberTextBoxTextValue) { return numberTextBoxTextValue.Equals(SPECIAL_NUMBER) }This will compile and always return false . 这将编译并始终返回false 。 While the following will give a compile error: 虽然以下将给出编译错误:
public const int SPECIAL_NUMBER = 213; public bool IsSpecialNumberEntered(string numberTextBoxTextValue) { return (numberTextBoxTextValue == SPECIAL_NUMBER); }We have had to solve a similar problem where someone compared enums of different type using Equals . 我们不得不解决一个类似的问题,即有人使用Equals比较了不同类型的枚举。 You are going to read over this MANY times before realising it is the cause of the bug. 您将要仔细阅读这多次,然后才意识到它是导致此错误的原因。 Especially if the definition of SPECIAL_NUMBER is not near the problem area. 特别是如果SPECIAL_NUMBER的定义不在问题区域附近。
This is why I am really against the use of Equals in situations where is it not necessary. 这就是为什么我真的反对在没有必要的情况下使用平等。 You lose a little bit of type-safety. 您会失去一些类型安全性。
There is practical difference between string.Equals and == string.Equals和==之间有实际的区别
bool result = false; object obj = "String"; string str2 = "String"; string str3 = typeof(string).Name; string str4 = "String"; object obj2 = str3; // Comparision between object obj and string str2 -- Com 1 result = string.Equals(obj, str2);// true result = String.ReferenceEquals(obj, str2); // true result = (obj == str2);// true // Comparision between object obj and string str3 -- Com 2 result = string.Equals(obj, str3);// true result = String.ReferenceEquals(obj, str3); // false result = (obj == str3);// false // Comparision between object obj and string str4 -- Com 3 result = string.Equals(obj, str4);// true result = String.ReferenceEquals(obj, str4); // true result = (obj == str4);// true // Comparision between string str2 and string str3 -- Com 4 result = string.Equals(str2, str3);// true result = String.ReferenceEquals(str2, str3); // false result = (str2 == str3);// true // Comparision between string str2 and string str4 -- Com 5 result = string.Equals(str2, str4);// true result = String.ReferenceEquals(str2, str4); // true result = (str2 == str4);// true // Comparision between string str3 and string str4 -- Com 6 result = string.Equals(str3, str4);// true result = String.ReferenceEquals(str3, str4); // false result = (str3 == str4);// true // Comparision between object obj and object obj2 -- Com 7 result = String.Equals(obj, obj2);// true result = String.ReferenceEquals(obj, obj2); // false result = (obj == obj2);// falseAdding Watch 添加手表
obj "String" {1#} object {string} str2 "String" {1#} string str3 "String" {5#} string str4 "String" {1#} string obj2 "String" {5#} object {string}Now look at {1#} and {5#} 现在来看{1#}和{5#}
obj , str2 , str4 and obj2 references are same. obj , str2 , str4和obj2引用相同。
obj and obj2 are object type and others are string type obj和obj2是object type ,其他是string type
Conclusion : 结论 :
com1 : result = (obj == str2);// true com1 :结果=(obj == str2); // true compares object and string so performs a reference equality check 比较object和string以便执行引用相等性检查 obj and str2 point to the same reference so the result is true obj和str2指向相同的引用,因此结果为true com2 : result = (obj == str3);// false com2 :结果=(obj == str3); //否 compares object and string so performs a reference equality check 比较object和string以便执行引用相等性检查 obj and str3 point to the different references so the result is false obj和str3指向不同的引用,因此结果为false com3 : result = (obj == str4);// true com3 :结果=(obj == str4); // true compares object and string so performs a reference equality check 比较object和string以便执行引用相等性检查 obj and str4 point to the same reference so the result is true obj和str4指向相同的引用,因此结果为true com4 : result = (str2 == str3);// true com4 :结果=(str2 == str3); // true compares string and string so performs a string value check 比较string和string以便执行字符串值检查 str2 and str3 are both "String" so the result is true str2和str3均为“字符串”,因此结果为true com5 : result = (str2 == str4);// true com5 :结果=(str2 == str4); // true compares string and string so performs a string value check 比较string和string以便执行字符串值检查 str2 and str4 are both "String" so the result is true str2和str4均为“字符串”,因此结果为true com6 : result = (str3 == str4);// true com6 :结果=(str3 == str4); // true compares string and string so performs a string value check 比较string和string以便执行字符串值检查 str3 and str4 are both "String" so the result is true str3和str4均为“字符串”,因此结果为true com7 : result = (obj == obj2);// false - compares object and object so performs a reference equality check - obj and obj2 point to the different references so the result is false com7 :result =(obj == obj2); // false-比较object和object从而执行引用相等性检查-obj和obj2指向不同的引用,因此结果为falseThere's a writeup on this article which you might find to be interesting, with some quotes from Jon Skeet. 这篇文章有一篇文章 ,您可能会发现它很有趣,并引用了Jon Skeet的话。 It seems like the use is pretty much the same. 看起来用途几乎相同。
Jon Skeet states that the performance of instance Equals "is slightly better when the strings are short—as the strings increase in length, that difference becomes completely insignificant." 乔恩·斯基特(Jon Skeet)指出,实例Equals的性能“在字符串较短的情况下会稍好一些-随着字符串长度的增加,这种差异变得完全无关紧要”。