问题
Possible Duplicate:
C#: String.Equals vs. ==
Hi to all.
Some time someone told me that you should never compare strings with == and that you should use string.equals(), but it refers to java.
¿What is the diference beteen == and string.equals in .NET c#?
回答1:
string == string
is entirely the same as String.Equals
. This is the exact code (from Reflector):
public static bool operator ==(string a, string b)
{
return Equals(a, b); // Is String.Equals as this method is inside String
}
回答2:
In C# there is no difference as the operator ==
and !=
have been overloaded in string type to call equals()
. See this MSDN page.
回答3:
== actually ends up executing String.Equals on Strings.
You can specify a StringComparision when you use String.Equals....
Example:
MyString.Equals("TestString", StringComparison.InvariantCultureIgnoreCase)
Mostly, I consider it a coding preference. Use whichever you prefer.
回答4:
Look here for a better description. As one answer stated
When == is used on an object type, it'll resolve to System.Object.ReferenceEquals.
Equals is just a virtual method and behaves as such, so the overridden version will be used (which, for string type compares the contents).
回答5:
The ==
operator calls the String.Equals
method. So at best you're saving a method call. Decompiled code:
public static bool operator ==(string a, string b)
{
return string.Equals(a, b);
}
回答6:
no difference, it's just an operator overload. for strings it's internally the same thing. however, you don't want to get in a habit of using == for comparing objects and that's why it's not recommended to use it for strings as well.
回答7:
In C# there's no difference for strings.
回答8:
If you dont care about the string's case and dont worry about cultural awarenes then it's the same...
来源:https://stackoverflow.com/questions/5796169/vs-string-equals-c-sharp-net