在 EditorConfig 中关闭 C# 变量丢弃

问题描述 投票:0回答:2

在 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;
}

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

_ =

我的 VSCode 设置:

{
  "settings": {
    "[csharp]": {
      "editor.defaultFormatter": "csharpier.csharpier-vscode",
      "editor.codeActionsOnSave": {
        "source.fixAll.csharp": true
      }
    },
    "omnisharp.enableEditorConfigSupport": true,
    "omnisharp.enableRoslynAnalyzers": true,
  }
}
c# visual-studio-code static-analysis omnisharp editorconfig
2个回答
11
投票

简短回答:

  • 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

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

提示: 这里是严重级别的选项。


0
投票

@Schmebi 和 @F.D.Castel 的综合答案。

使用这些设置:

csharp_style_unused_value_assignment_preference = discard_variable:none
csharp_style_unused_value_expression_statement_preference = discard_variable:none
© www.soinside.com 2019 - 2024. All rights reserved.