字符串比较等效项
我相信这两行是等效的,但在遇到一个奇怪的问题后,我不再相信情况是这样。
String mimeType = context.Request.ContentType;
(String.Compare("text/xml", mimeType, true) == 0))
与 :
context.Request.ContentType.ToLower().Equals("text/xml")
它们在 CLR 中的实现有什么不同吗?
I believe these 2 lines are equivalent but after running into a strange issue I no longer believe this to be the case.
String mimeType = context.Request.ContentType;
(String.Compare("text/xml", mimeType, true) == 0))
is the same as :
context.Request.ContentType.ToLower().Equals("text/xml")
Are their implementations in the CLR any different?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
它们并不等同,ToLower/ToUpper 可能存在一些本地化问题。比较两个字符串而不区分大小写的方法(考虑到其中一个字符串可能为 null,这就是我不喜欢 str1.Equals 方法的原因)是静态 String.Equals 方法:
They are not equivalent, and ToLower/ToUpper may have some localization issues. The way to compare two strings without case-sensitivity (considering one of the strings may be null, which is why I don't like the str1.Equals method) is the static String.Equals method:
它们并不完全等同;请参阅此处。
以下是进行不区分大小写比较的正确方法:
这种方法也会更有效,因为它不会为小写副本分配单独的字符串。
They are not completely equivalent; see here.
Here is the correct way to do a case insensitive comparison:
This way will also be more efficient becasue it doesn't allocate a separate string for the lowercase copy.
除了其他答案(@SLaks,@Serhio)之外,我还有义务指出 .ToLower() 生成另一个字符串。据我所知,比较没有。如果应用程序中的过多字符串生成在频繁调用的代码中,则可能会在内存使用和性能方面造成影响。
In addition to the other answers (@SLaks, @Serhio), I also feel obligated to point out that .ToLower() generates another string. Compare does not as far as I know. Excessive string generation in an app can come back to bite you in terms of memory usage and performance if it is in frequently called code.
.NET 中 Compare(string, string, boolean) 的实现:
和 Equals
So 是不同一件事。
the implementation of Compare(string, string, boolean) in .NET:
and Equals
So, is NOT the same thing.