C# character string equal sexual problems:
and compare ==
Equals()
C# offers two comparison string operators:
. Although they seem to be able to swap, they show unique behaviors and may lead to unexpected results. Let's explore this language problem through a specific scene. ==
Equals()
In a Silverlight application, one condition compares two string:
Strangely,
<code class="language-csharp">if (((ListBoxItem)lstBaseMenu.SelectedItem).Content.Equals("Energy Attack")) { // 执行代码 } if (((ListBoxItem)lstBaseMenu.SelectedItem).Content == "Energy Attack") { // 执行代码 }</code>
call back true. Why is there such a difference? ==
Equals()
The answer lies in the underlying implementation of these operators. When used with an object expression,
. This method compares the object reference, not the ==
content System.Object.ReferenceEquals
. In this case, the two string are stored in different memory positions, so return to false.
ReferenceEquals
On the other hand, is a virtual method that can be rewritten by derived type. For string types, the rewrite version of the actual
, thereby returning True. Equals
Therefore, for comparison of the string of string, it is recommended to use , it is more intuitive, and it performs the content -based comparison.
The above is the detailed content of C# String Comparison: When Should I Use `==` vs. `Equals()`?. For more information, please follow other related articles on the PHP Chinese website!