EditorConfig:允许或强制私有字段以下划线开头

Flo*_*ish 8 c# warnings suppress-warnings visual-studio-code editorconfig

编辑:我正在使用 VS Code。

对于使用下划线作为私有字段前缀的代码,我收到以下警告:

Naming rule violation: Prefix '_' is not expected [MyProject]csharp(IDE1006)
Run Code Online (Sandbox Code Playgroud)

下面是我的代码:

namespace MyProject
{
    public class Dog
    {
        // Naming rule violation: Prefix '_' is not expected [MyProject]csharp(IDE1006)
        private int _age;

        public int Age()
        {
            return _age;
        }

        public void SetAge(int age)
        {
            _age = age;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

以下是我的.editorconfig文件:

[*.cs]

# Require private fields to begin with an underscore (_).
dotnet_naming_rule.instance_fields_should_be_camel_case.severity = warning
dotnet_naming_rule.instance_fields_should_be_camel_case.symbols = instance_fields
dotnet_naming_rule.instance_fields_should_be_camel_case.style = instance_field_style
dotnet_naming_symbols.instance_fields.applicable_kinds = field
dotnet_naming_style.instance_field_style.capitalization = camel_case
dotnet_naming_style.instance_field_style.required_prefix = _
Run Code Online (Sandbox Code Playgroud)

我还发布了我的Directory.Build.props文件,以防它与我.editorconfig上面的文件冲突。我将其设置为尽可能严格,这样我就可以修复(或根据需要抑制)更严格的 C# 编译器会引发的所有警告:

<Project>
  <PropertyGroup>
    <Features>strict</Features>
    <WarningLevel>9999</WarningLevel>
  </PropertyGroup>
</Project>
Run Code Online (Sandbox Code Playgroud)

我正在寻找一种解决方案,可以使 C# 的编译器尽可能严格,并且可以在私有字段前添加下划线,可以允许它们,也可以最好强制执行它们(没有下划线的私有字段将收到警告)。

Flo*_*ish 17

我在这里研究了微软的文档后终于弄清楚了

显然,条目的中间部分是一个标识符,可以设置为我们想要的任何内容。

我创建了一条新规则,要求私有字段以下划线开头并采用驼峰式大小写。

以下是我的新.editorconfig文件:

# Define what we will treat as private fields.
dotnet_naming_symbols.private_fields.applicable_kinds = field
dotnet_naming_symbols.private_fields.applicable_accessibilities = private
# Define rule that something must begin with an underscore and be in camel case.
dotnet_naming_style.require_underscore_prefix_and_camel_case.required_prefix = _
dotnet_naming_style.require_underscore_prefix_and_camel_case.capitalization = camel_case
# Appy our rule to private fields.
dotnet_naming_rule.private_fields_must_begin_with_underscore_and_be_in_camel_case.symbols = private_fields
dotnet_naming_rule.private_fields_must_begin_with_underscore_and_be_in_camel_case.style = require_underscore_prefix_and_camel_case
dotnet_naming_rule.private_fields_must_begin_with_underscore_and_be_in_camel_case.severity = warning
Run Code Online (Sandbox Code Playgroud)

非常感谢所有提供帮助的人,我希望这对那里的人有所帮助。