C#中字符串比较方法的差异 [英] Differences in string compare methods in C#
问题描述
在 C# 中比较字符串非常简单.事实上,有几种方法可以做到.我在下面的块中列出了一些.我很好奇的是它们之间的区别以及何时应该使用它们而不是其他?是否应该不惜一切代价避免?还有更多我没有列出的吗?
Comparing string in C# is pretty simple. In fact there are several ways to do it. I have listed some in the block below. What I am curious about are the differences between them and when one should be used over the others? Should one be avoided at all costs? Are there more I haven't listed?
string testString = "Test";
string anotherString = "Another";
if (testString.CompareTo(anotherString) == 0) {}
if (testString.Equals(anotherString)) {}
if (testString == anotherString) {}
(注意:我在这个例子中寻找相等,不小于或大于但也可以对此发表评论)
(Note: I am looking for equality in this example, not less than or greater than but feel free to comment on that as well)
推荐答案
以下是这些函数的工作规则:
Here are the rules for how these functions work:
stringValue.CompareTo(otherStringValue)
null
出现在字符串之前- 它使用
CultureInfo.CurrentCulture.CompareInfo.Compare
,这意味着它将使用文化相关的比较.这可能意味着ß
将等于德国的SS
或类似的
null
comes before a string- it uses
CultureInfo.CurrentCulture.CompareInfo.Compare
, which means it will use a culture-dependent comparison. This might mean thatß
will compare equal toSS
in Germany, or similar
stringValue.Equals(otherStringValue)
null
不等于任何东西- 除非您指定
StringComparison
选项,否则它将使用看起来像直接序数相等性检查的内容,即ß
与SS
不同>,在任何语言或文化中
null
is not considered equal to anything- unless you specify a
StringComparison
option, it will use what looks like a direct ordinal equality check, i.e.ß
is not the same asSS
, in any language or culture
stringValue == otherStringValue
- 与
stringValue.Equals()
不同. ==
运算符调用静态Equals(string a, string b)
方法(该方法又转到内部EqualsHelper
进行比较.- 在
null
字符串上调用.Equals()
会得到null
引用异常,而在==
上会不是.
- Is not the same as
stringValue.Equals()
. - The
==
operator calls the staticEquals(string a, string b)
method (which in turn goes to an internalEqualsHelper
to do the comparison. - Calling
.Equals()
on anull
string getsnull
reference exception, while on==
does not.
Object.ReferenceEquals(stringValue, otherStringValue)
只需检查引用是否相同,即它不仅仅是具有相同内容的两个字符串,而是将一个字符串对象与其自身进行比较.
Just checks that references are the same, i.e. it isn't just two strings with the same contents, you're comparing a string object with itself.
请注意,对于上面使用方法调用的选项,有更多选项的重载来指定如何比较.
Note that with the options above that use method calls, there are overloads with more options to specify how to compare.
如果您只想检查相等性,我的建议是决定是否要使用依赖于文化的比较,然后使用 .CompareTo
或 .Equals
,取决于选择.
My advice if you just want to check for equality is to make up your mind whether you want to use a culture-dependent comparison or not, and then use .CompareTo
or .Equals
, depending on the choice.
这篇关于C#中字符串比较方法的差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!