在.Net 5中string.IndexOf得到不同的结果 [英] string.IndexOf get different result in .Net 5

查看:37
本文介绍了在.Net 5中string.IndexOf得到不同的结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我在 .Net Core 3.1 中运行以下代码时,我得到 6

When i run following code in .Net Core 3.1 i get 6

//Net Core 3.1
string s = "Hello\r\nworld!";
int idx = s.IndexOf("\n");
Console.WriteLine(idx);

结果

6

但是当我在 .Net 5 中运行此代码时,我得到了不同的结果.为什么?

but when i run this code in .Net 5 i get different result. why?

//NET 5
string s = "Hello\r\nworld!";
int idx = s.IndexOf("\n");
Console.WriteLine(idx);

结果

-1

推荐答案

注释和@Ray的答案都包含了原因.

The comments and @Ray's answer contain the reason.

尽管入侵 .csproj runtimeconfig.json 文件可能会节省您的时间,但真正的解决方案是显式指定比较:

And though hacking the .csproj or runtimeconfig.json file may save your day the real solution is to specify the comparison explicitly:

// this returns the expected result
int idx = s.IndexOf("\n", StringComparison.Ordinal);

由于某种原因, IndexOf(string)默认使用当前的区域性比较,即使在具有与区域设置不同的环境中执行您的应用程序的情况下,即使使用早期.NET版本也可能引起意外.

For some reason IndexOf(string) defaults to use current culture comparison, which can cause surprises even with earlier .NET versions when your app is executed in an environment that has different regional settings than yours.

使用特定文化的搜索实际上是一种非常罕见的情况(例如,可以在浏览器,书籍阅读器或UI搜索中有效),并且比常规搜索要慢得多.

Using a culture-specific search is actually a very rare scenario (can be valid in a browser, book reader or UI search, for example) and it is much slower than ordinal search.

同一问题适用于 StartsWith / EndsWith /包含/ ToUpper / ToLower 甚至 ToString Parse 方法(尤其是在使用浮点类型时),因为这些默认情况下也使用当前区域性,这可以作为很多陷阱.但是,如果您不使用特定的比较或区域性,最近的代码分析器(例如FxCop,ReSharper)会警告您.建议在产品代码中为这些问题设置较高的严重性.

The same issue applies for StartsWith/EndsWith/Contains/ToUpper/ToLower and even ToString and Parse methods of formattable types (especially when using floating-point types) as these also use the current culture by default, which can be the source of many gotchas. But recent code analyzers (eg. FxCop, ReSharper) can warn you if you don't use a specific comparison or culture. It is recommended to set a high severity for these issues in a product code.

这篇关于在.Net 5中string.IndexOf得到不同的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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