'==' vs string.equals c# .net [duplicate]

三世轮回 提交于 2019-12-10 14:13:15

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!