【问题标题】:How can I enforce code styles for C#/.NET, like IDE0058, IDE0059 and IDE0060?如何强制 C#/.NET 的代码样式,如 IDE0058、IDE0059 和 IDE0060?
【发布时间】:2022-01-27 17:00:01
【问题描述】:

我正在研究强制执行代码样式,并开始在我的 .editorconfig 中实现 IDE0058IDE0059IDE0060,如下所示:

csharp_style_unused_value_expression_statement_preference = discard_variable:error
csharp_style_unused_value_assignment_preference = discard_variable:error
dotnet_code_quality_unused_parameters = all:error

当我在 Windows 上的 Visual Studio 2022 中运行构建时,我确实收到了错误,尽管构建仍然成功。 但是,当我从命令行运行 dotnet build 时,我没有收到任何错误,并且当我搜索样式代码时,我找不到任何提及它们。

我同事在他的macbook上测试了一下,mac版的visual studio没有报错。命令行也没有。

在我们的 gitlab 管道中,我们还运行了dotnet build,它也顺利通过了。

在我们使用 .NET 6.0 的所有环境中。

是否可以使用.editorconfig 强制执行这些代码样式?如果有,怎么做?

如果不是,如何强制执行代码样式?

【问题讨论】:

    标签: c# .net gitlab dotnet-cli


    【解决方案1】:

    将以下行添加到 csproj 文件

    <PropertyGroup>
        <EnforceCodeStyleInBuild>true</EnforceCodeStyleInBuild>
        <AnalysisLevel>6.0-recommended</AnalysisLevel>
    </PropertyGroup>
    

    然后在 editorconfig 中另外添加到您现有的规则

    dotnet_diagnostic.IDE0058.severity = error
    dotnet_diagnostic.IDE0059.severity = error
    dotnet_diagnostic.IDE0060.severity = error
    

    【讨论】:

      【解决方案2】:

      您需要启用项目属性:

      1. 右键单击项目
      2. 点击“构建”
      3. Treat warnings as errors设置为All

      但是,如果你这样做,它只会被添加到当前配置,可能是Debug

      您可以通过 UI 手动完成这两种配置(DebugRelease)。

      或者您可以编辑您的.csproj 文件。

      如果您通过 UI 设置 Treat warnings as errors: All,则会添加此内容。

        <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
          <TreatWarningsAsErrors>true</TreatWarningsAsErrors>
          <WarningsAsErrors />
        </PropertyGroup>
      

      您可以复制它并更改配置:

      如果您通过 UI 设置 Treat warnings as errors: All,则为 ded。

        <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|AnyCPU'"> // Changed `Debug` to `Release`
          <TreatWarningsAsErrors>true</TreatWarningsAsErrors>
          <WarningsAsErrors />
        </PropertyGroup>
      

      【讨论】:

      • 谢谢,这确实捕获了很多警告,但似乎仍然没有捕获 IDE0058、IDE0059 和 IDE0060。你知道这些有没有设置?
      猜你喜欢
      • 1970-01-01
      • 2011-11-13
      • 2011-09-22
      • 2011-04-02
      • 1970-01-01
      • 2019-01-31
      • 1970-01-01
      • 1970-01-01
      • 2021-03-03
      相关资源
      最近更新 更多