.NET 中的字符串比较
(.NET) 之间有什么区别(以 bref 表示)
myString == otherString
(.NET)和
myString.CompareTo(otherString) == 0
What is the difference (in bref) between (.NET)
myString == otherString
and
myString.CompareTo(otherString) == 0
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
没有什么区别,除了当 myString 为
null
时,在这种情况下myString.CompareTo(otherString)
会抛出错误 (NullReferenceException
)。另外,使用CompareTo
比==
慢一点。仅当您有兴趣了解某个字符串按字母顺序排序时是否位于另一个字符串之前或之后时,才使用
CompareTo
。例如,"Car".CompareTo("Cat")
返回 -1,因为按字母顺序排序时,“Car”位于“Cat”之前。There's no difference, except when myString is
null
, in which casemyString.CompareTo(otherString)
throws an error (NullReferenceException
). Also, usingCompareTo
is a little bit slower than==
.Only use
CompareTo
when you are interested in knowing if a string is before or after another one in an alphabetical sorting of them. For example"Car".CompareTo("Cat")
returns -1 because "Car" is before "Cat" when ordered alphabetically.CompareTo
应该仅用于评估排序。无论出于何种原因,两个字符串出于排序目的进行比较时可能相同,但不应被视为相等(即==
和Equals
可能返回假)。
引用文档:
添加了强调 - 请注意,它没有说这两个对象是相等的。
CompareTo
should only be used for assessing ordering. It may be that, for whatever reason, two strings compare the same for ordering purposes, but should not be considered equal (that is,==
andEquals
may returnfalse
).To quote the documentation:
Emphasis added - note that it does not say that the two objects are equal.
假设你的意思
是没有明显的差异。
Assuming that you meant
there is no visible difference.
假设您的意思是 == 而不是 =
CompareTo 实现了 IComparable 接口。它返回一个整数。
Assuming you meant == and not =
CompareTo implements the IComparable interface. It returns an integer.
来自此处:
Equals
方法更合适。从此处开始,Equals
和==< 之间的区别/code> 的特点是
Equals
要求其参数非空,而==
则不需要。另外,==
被实现为使用Equals
,因此Equals
将始终具有更好的性能。From here:
The
Equals
method is more appropriate. From here, the difference betweenEquals
and==
is thatEquals
requires its parameter to be non-null and==
does not. Plus,==
is implemented to useEquals
soEquals
will always have better performance.myString.CompareTo(otherString) 方法的主要目的是用于排序或按字母顺序排列
运营。当主要目的是检查字符串的相等性时,不应使用它。
要确定两个字符串是否相等,请调用 Equals 方法。”
当仅查找相等性时,最好使用 .Equals 而不是 .CompareTo。因为我也认为编译器比 == 操作更快。
The myString.CompareTo(otherString) method main purpose is to be used with sorting or alphabetizing
operations. It should not be used when the main purpose is to check the equality of strings.
To determine whether two strings are equivalent, call the Equals method."
It's better to use .Equals instead of .CompareTo when looking solely for equality. since I also think it is faster for the compiler than the == operation.