The difference between understanding C# == and equals ()
In C#, you may encounter this situation: Use == The comparative comparison of the component to compare the two string back to false, and the equals () method returns true. To understand this behavior, you must master the fundamental differences of these operators.
When used for objects, the value of == The value of the operator is System.object.referenceequals. This means that it checks whether the two string objects reference the same object in memory. Instead, Equals () is a virtual method that can be rewritten by custom types (including string).
For the string, use the rewriting version of Equals () to check the actual content of the string. Therefore, if you compare two string with the same character but stored in different memory positions, == will return to false because they are not referenced in the same object, and Equals () will return to TRUE because they are equal.
Code example:
Consider the following code fragment:
In this code, these two conditions will compare the Content properties of the selected listboxitem with the string "Energy Attack". Although the first condition of EQUALS () is calculated as true, if the Content property is a new string object, the second condition of == may be calculated as false. This is because the == operator check identification, and two different string objects with the same value are different.
<code class="language-c#">if (((ListBoxItem)lstBaseMenu.SelectedItem).Content.Equals("Energy Attack")) { // 执行代码 } if (((ListBoxItem)lstBaseMenu.SelectedItem).Content == "Energy Attack") { // 执行代码 }</code>
The above is the detailed content of C# String Comparison: When Does == Differ From Equals()?. For more information, please follow other related articles on the PHP Chinese website!