踩坑记录之 -- String.IndexOf 在 .Net5 和 .Netcore3 中返回值不一样

时间:2021-07-14 11:54:49   收藏:0   阅读:16

.Net Core3.1 下

运行此段代码

    class Program
    {
        static void Main(string[] args)
        {
            // .NET Core 3.1
            string s = "Hello\r\nworld!";
            int idx = s.IndexOf("\n");
            Console.WriteLine(idx);
        }
    }

返回结果为 6

.Net5 下

运行同样代码

    class Program
    {
        static void Main(string[] args)
        {
            // .NET Core 3.1
            string s = "Hello\r\nworld!";
            int idx = s.IndexOf("\n");
            Console.WriteLine(idx);
        }
    }

返回结果为 -1

解决

全局

2019年5月, windows 做了一个补丁升级,让后续的 .NET 全球化API 由原来的 NLS 切换到了 ICU 模式,这就是在后续的 .NET5 表现不一致的根源,如果你想退回到 NLS,需要做如下配置。

<ItemGroup>
  <RuntimeHostConfigurationOption Include="System.Globalization.UseNls" Value="true" />
</ItemGroup>
{
  "runtimeOptions": {
     "configProperties": {
       "System.Globalization.UseNls": true
      }
  }
}

局部

你可以使用 StringComparison.Ordinal 来指定字符串比较规则

            string s = "Hello\r\nworld!";
            int idx = s.IndexOf("\n",StringComparison.Ordinal);
            Console.WriteLine(idx);

输出结果为 6

技术分享图片

            string s = "Hello\r\nworld!";

            var comparisons = (StringComparison[])Enum.GetValues(typeof(StringComparison));
            foreach (var item in comparisons)
            {
                Console.WriteLine($"{item}: {s.IndexOf("\n", item)}");
            }

结果
技术分享图片

可得 通过StringComparison.Ordinal/OrdinalIgnoreCase 可获取同样的Index

原文:https://www.cnblogs.com/Alicia-meng/p/15009467.html

评论(0
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!