在 EditorConfig 中关闭 C# 变量丢弃

Snæ*_*ørn 7 c# static-analysis omnisharp visual-studio-code editorconfig

当在 VSCode 中格式化和自动修复 C# 文件中的“linting”错误时,它似乎丢弃了我未使用的变量。基本上它放在_ =一切的前面。

它这样做是因为csharp_style_unused_value_assignment_preference = discard_variable这是默认的。 https://learn.microsoft.com/da-dk/dotnet/fundamentals/code-analysis/style-rules/ide0059#csharp_style_unused_value_assignment_preference

// csharp_style_unused_value_assignment_preference = discard_variable
int GetCount(Dictionary<string, int> wordCount, string searchWord)
{
    _ = wordCount.TryGetValue(searchWord, out var count);
    return count;
}

// csharp_style_unused_value_assignment_preference = unused_local_variable
int GetCount(Dictionary<string, int> wordCount, string searchWord)
{
    var unused = wordCount.TryGetValue(searchWord, out var count);
    return count;
}
Run Code Online (Sandbox Code Playgroud)

那很整齐。但我该如何关闭它呢?因此,当我在 VSCode 中对 C# 文件应用格式时,它不会添加_ =.

我的 VSCode 设置:

{
  "settings": {
    "[csharp]": {
      "editor.defaultFormatter": "csharpier.csharpier-vscode",
      "editor.codeActionsOnSave": {
        "source.fixAll.csharp": true
      }
    },
    "omnisharp.enableEditorConfigSupport": true,
    "omnisharp.enableRoslynAnalyzers": true,
  }
}
Run Code Online (Sandbox Code Playgroud)

Sch*_*ebi 12

简短回答:

  • csharp_style_unused_value_assignment_preference = discard_variable:none

或者,如果您想使用局部变量:

  • csharp_style_unused_value_assignment_preference = unused_local_variable:suggestion

长答案:

可能是您自己找到答案的最简单方法:

  1. 在 IDE 中打开错误列表/面板。
  2. 在 Visual Studio(可能还有其他 IDE)中,您可以单击代码打开文档或在线搜索代码。
  3. 阅读文档

您现在有两个选择:

  • 直接为该代码设置级别 dotnet_diagnostic.[ErrorCode].severity = none

    使用代码时应添加注释。

  • 如果定义了一个属性,您可以使用该属性。propertie_name = value:severity

    我建议使用第二种方式,以便于阅读,您也可以将代码添加为注释。

提示: 以下是严重性级别的选项。

  • 如果您正在阅读本文,您可能也想关闭“csharp_style_unused_value_expression_statement_preference”(将其设置为“discard_variable:none”)。 (4认同)