使用==还是equals的字符串比较 [英] Using == or Equals for string comparison
问题描述
在某些语言(如C ++),你不能使用类似==操作符进行字符串比较,将比较字符串对象的地址,而不是字符串本身。然而,在C#中,你可以使用==来比较字符串,它实际上将比较字符串的内容。但也有字符串函数来处理这样的比较,所以我的问题是;你应该?
In some languages (e.g. C++) you can't use operators like == for string comparisons as that would compare the address of the string object, and not the string itself. However, in C# you can use == to compare strings, and it will actually compare the content of the strings. But there are also string functions to handle such comparisons, so my question is; should you?
由于两个字符串:
string aa = "aa";
string bb = "bb";
如果您对它们进行比较是这样的:
Should you compare them like this:
bool areEqual = (aa == bb);
还是应该用平等的功能,像这样的:
Or should you use the Equal function, like this:
bool areEqual = aa.Equals(bb);
有什么技术区别呢?最佳做法还是合理的论据?
Is there any technical difference anyway? Or reasonable arguments for best practice?
推荐答案
我不会用:
aa.Equals(bb)
除非我知道 AA
不可能的可能的为空。我可能是:
unless I knew aa
couldn't possibly be null. I might use:
string.Equals(aa,bb)
但是我主要使用它,我想用特定的一个 StringComparison
模式(不变,顺序,不区分大小写,等等)。虽然我也可以使用 StringComparer
的实现,因为它们更容易一点抽象的(例如,通过成词典<字符串,富>
为不区分大小写的有序字典)。对于通用的用法,
But I'd mainly use that it I wanted to use one of the specific StringComparison
modes (invariant, ordinal, case-insensitive, etc). Although I might also use the StringComparer
implementations, since they are a bit easier to abstract (for example, to pass into a Dictionary<string, Foo>
for a case-insensitive ordinal dictionary). For general purpose usage,
a == b
是好的。
这篇关于使用==还是equals的字符串比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!