ToLowerInvariant()有什么问题吗?

我有以下一行代码:

var connectionString = configItems.
Find(item => item.Name.ToLowerInvariant() == "connectionstring");

VS 2010代码分析告诉我以下内容:

警告7CA1308: Microsoft。全球化: 在方法中... 将对‘ string.ToLowerInvariable ()’的调用替换为 String.ToUpperInvari()。

这是否意味着 ToUpperInvariant()更可靠?

25620 次浏览

Google gives a hint pointing to CA1308: Normalize strings to uppercase

It says:

Strings should be normalized to uppercase. A small group of characters, when they are converted to lowercase, cannot make a round trip. To make a round trip means to convert the characters from one locale to another locale that represents character data differently, and then to accurately retrieve the original characters from the converted characters.

So, yes - ToUpper is more reliable than ToLower.

In the future I suggest googling first - I do that for all those FxCop warnings I get thrown around ;) Helps a lot to read the corresponding documentation ;)

Besides what TomTom says, .net is optimized for string comparison in upper case. So using upper invariant is theoretically faster than lowerinvariant.

This is indeed stated in CLR via C# as pointed out in the comments. Im not sure if this is of course really true since there is nothing to be found on MSDN about this topic. The string comparison guide on msdn mentions that toupperinvariant and tolowerinvariant are equal and does not prefer the former.