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

查看:360
本文介绍了在字符串比较的差异在C#中的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C#中比较字符串是pretty简单。事实上,有几种方法可以做到这一点。我列出了一些在下面的块。我很好奇,它们之间的差异,当一个人应在他人使用?如果一个不惜一切代价避免?是否有更多我没有列出?

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. 空而来的字符串

  2. 它使用CultureInfo.CurrentCulture.CompareInfo.Compare,这意味着它将使用文化依赖性比较。这可能意味着,SS将在德国比较等于SS或类似

stringValue.Equals(otherStringValue):


  1. 空不被认为等于什么

  2. 除非指定StringComparison选择,它将使用什么看起来像一个直接序平等的检查,即得。 SS是不一样的SS,以任何语言或文化

stringValue的== otherStringValue:


  1. 是不一样的stringValue.Equals()。

  2. 的==操作符调用静态等于(字符串,字符串二)方法(这反过来又转到内部EqualsHelper做比较。

  3. 调用.Equals()上的一个空字符串得到空引用异常,而在==没有。

Object.ReferenceEquals(stringValue的,otherStringValue):

只需检查该参考文献是一样的,即它不只是两个字符串具有相同的内容,你是一个比较字符串对象与自身。

Just checks that references are the same, ie. 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 wether you want to use a culture-dependant comparison or not, and then use .CompareTo or .Equals, depending on the choice.

这篇关于在字符串比较的差异在C#中的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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