简体   繁体   English

使用InvariantCultureIgnoreCase而不是ToUpper进行不区分大小写的字符串比较

[英]Using InvariantCultureIgnoreCase instead of ToUpper for case-insensitive string comparisons

On this page , a commenter writes: 这个页面上 ,一位评论者写道:

Do NOT ever use .ToUpper to insure comparing strings is case-insensitive. 不要使用.ToUpper来确保比较字符串不区分大小写。

Instead of this: 而不是这个:

type.Name.ToUpper() == (controllerName.ToUpper() + "Controller".ToUpper())) 

Do this: 做这个:

type.Name.Equals(controllerName + "Controller", 
     StringComparison.InvariantCultureIgnoreCase)

Why is this way preferred? 为什么这种方式更受欢迎?

Here is the answer in details .. The Turkey Test ( read section 3 ) 以下是详细答案。 土耳其测试阅读第3部分

As discussed by lots and lots of people, the "I" in Turkish behaves differently than in most languages. 正如许多人所讨论的那样,土耳其语中的“我”与大多数语言的行为不同。 Per the Unicode standard, our lowercase "i" becomes "İ" (U+0130 "Latin Capital Letter I With Dot Above") when it moves to uppercase. 根据Unicode标准,当它移动到大写时,我们的小写“i”变为“İ”(U + 0130“Latin Capital Letter I With Dot Above”)。 Similarly, our uppercase "I" becomes "ı" (U+0131 "Latin Small Letter Dotless I") when it moves to lowercase. 同样,当它移动到小写时,我们的大写“I”变成“ı”(U + 0131“Latin Small Letter Dotless I”)。

Fix : Again, use an ordinal (raw byte) comparer, or invariant culture for comparisons unless you absolutely need culturally based linguistic comparisons (which give you uppercase I's with dots in Turkey) 修复 :再次使用序数(原始字节)比较器或不变文化进行比较,除非你绝对需要基于文化的语言比较(在土耳其给你大写字母I点)

And according to Microsoft you should not even be using the Invariant... but the Ordinal... ( New Recommendations for Using Strings in Microsoft .NET 2.0 ) 根据微软的说法,你甚至不应该使用Invariant ......而是Ordinal ...( 在Microsoft .NET 2.0中使用字符串的新建议

In short, it's optimized by the CLR (less memory as well). 简而言之,它通过CLR进行了优化(内存也更少)。

Further, uppercase comparison is more optimized than ToLower(), if that tiny degree of performance matters. 此外,如果这种微小的性能很重要,则大写比较比ToLower()更优化。

In response to your example there is a faster way yet : 为了回应您的示例,还有一种更快的方法

String.Equals(type.Name, controllerName + "Controller", 
              StringComparison.InvariantCultureIgnoreCase);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM