C#中字符串比较方法的差异 [英] Differences in string compare methods in C#

查看:31
本文介绍了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)

  1. null 出现在字符串之前
  2. 它使用 CultureInfo.CurrentCulture.CompareInfo.Compare,这意味着它将使用文化相关的比较.这可能意味着 ß 将等于德国的 SS 或类似的
  1. null comes before a string
  2. it uses CultureInfo.CurrentCulture.CompareInfo.Compare, which means it will use a culture-dependent comparison. This might mean that ß will compare equal to SS in Germany, or similar

stringValue.Equals(otherStringValue)

  1. null 不等于任何东西
  2. 除非您指定StringComparison 选项,否则它将使用看起来像直接序数相等性检查的内容,即ßSS 不同>,在任何语言或文化中
  1. null is not considered equal to anything
  2. unless you specify a StringComparison option, it will use what looks like a direct ordinal equality check, i.e. ß is not the same as SS, in any language or culture

stringValue == otherStringValue

  1. stringValue.Equals() 不同.
  2. == 运算符调用静态 Equals(string a, string b) 方法(该方法又转到内部 EqualsHelper进行比较.
  3. null 字符串上调用 .Equals() 会得到 null 引用异常,而在 == 上会不是.
  1. Is not the same as stringValue.Equals().
  2. The == operator calls the static Equals(string a, string b) method (which in turn goes to an internal EqualsHelper to do the comparison.
  3. Calling .Equals() on a null string gets null 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆