string.IndexOf 在 .NET 5.0 中返回不同的值 [英] string.IndexOf returns different value in .NET 5.0

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

问题描述

当我在 .NET Core 3.1 中运行以下代码时,我得到 6 作为返回值.

When I run the following code in .NET Core 3.1, I get 6 as the return value.

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

结果:

6

但是当我在 .NET 5.0 中运行此代码时,我得到了不同的结果.为什么会发生这种情况?

But when I run this code in .NET 5.0, I get a different result. Why does this happen?

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

结果:

-1

推荐答案

评论和@Ray 的回答包含原因.

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

虽然破解 .csprojruntimeconfig.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/Contains/ToUpper/ToLower 甚至 ToStringParse 可格式化类型的方法(尤其是在使用浮点类型时),因为这些默认情况下也使用当前区域性,这可以作为许多问题.但是,如果您不使用特定的比较或文化,最近的代码分析器(例如 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.

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

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