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

2019-06-19 18:03发布

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#?

8条回答
三岁会撩人
2楼-- · 2019-06-19 18:22

In C# there is no difference as the operator == and != have been overloaded in string type to call equals(). See this MSDN page.

查看更多
做个烂人
3楼-- · 2019-06-19 18:27

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);
}
查看更多
祖国的老花朵
4楼-- · 2019-06-19 18:27

If you dont care about the string's case and dont worry about cultural awarenes then it's the same...

查看更多
萌系小妹纸
5楼-- · 2019-06-19 18:32

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).

查看更多
smile是对你的礼貌
6楼-- · 2019-06-19 18:38

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
}
查看更多
仙女界的扛把子
7楼-- · 2019-06-19 18:44

== 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.

查看更多
登录 后发表回答