【问题标题】:Dotnet Core - Getting a warning on 'string.Replace(string, string?)' saying use 'string.Replace(string, string?, System.StringComparison)'Dotnet Core - 在 'string.Replace(string, string?)' 上收到警告说使用 'string.Replace(string, string?, System.StringComparison)'
【发布时间】:2020-01-06 13:49:46
【问题描述】:

我收到以下关于“替换”的警告

> Severity  Code    Description Project File    Line    Suppression State
> Warning   CA1307  The behavior of 'string.Replace(string, string?)' could
> vary based on the current user's locale settings. Replace this call in
> 'JobsLedger.API.ControllerServices.Common.OrderAndFIlterHelpers.ODataProcessQuery.ProcessQuery(string)'
> with a call to 'string.Replace(string, string?,
> System.StringComparison)'.    JobsLedger.API  C:\Users\simon\OneDrive\Documents\1.0
> - AURELIA\1.0 - JobsLedgerSPA -ASPNET CORE 3.1\JobsLedger.API\ControllerServices\Common\OrderAndFIlterHelpers\ODataProcessQuery.cs    38  Active

我不知道如何重新配置​​以下内容以考虑“System.StringComparison”:

                            .Replace("and", "&")
                            .Replace("substringof", string.Empty)
                            .Replace("(", string.Empty)
                            .Replace(")", string.Empty)
                            .Replace("'", string.Empty)
                            .Replace(" ", string.Empty)
                            .Replace("eq", ",")

每一行都抛出了一个警告..

我正在使用 VS2019,这些警告来自 Roslyn 编译器。我想摆脱警告..如何重写它以考虑替换的“System.StringComparison”部分?

【问题讨论】:

  • 您可以将附加参数StringComparison 传递给Replace 方法或配置警告严重性
  • 我知道国际化风靡一时,但您正在用 ASCII 替换 ASCII,您可能只想取消警告。

标签: c# visual-studio roslyn-code-analysis


【解决方案1】:

只是...告诉它你想要什么比较类型;例如,对于序数忽略大小写替换:

    .Replace("and", "&", StringComparison.OrdinalIgnoreCase)
    .Replace("substringof", string.Empty, StringComparison.OrdinalIgnoreCase)
    .Replace("(", string.Empty, StringComparison.OrdinalIgnoreCase)
    .Replace(")", string.Empty, StringComparison.OrdinalIgnoreCase)
    .Replace("'", string.Empty, StringComparison.OrdinalIgnoreCase)
    .Replace(" ", string.Empty, StringComparison.OrdinalIgnoreCase)
    .Replace("eq", ",", StringComparison.OrdinalIgnoreCase);

有关每个选项的作用的描述,请查看StringComparison。一般来说,您不应该使用CurrentCulture / CurrentCultureIgnoreCase 进行硬编码的类系统替换;基于文化的替换对于面向用户的替换更为典型(想想:ctrl+f)。作为旁注,使用string.Empty 比使用更清晰的(IMO)"" 确实没有任何好处。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-12-14
    • 2018-10-15
    • 2014-12-05
    • 2019-08-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多