string.IndexOf get different result in .Net 5

前端 未结 2 1836
死守一世寂寞
死守一世寂寞 2021-02-08 07:14

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

//Net Core 3.1
string s = "Hello\\r\\nwor         


        
2条回答
  •  情歌与酒
    2021-02-08 07:34

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

    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);
    

    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.

    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.

    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.

提交回复
热议问题