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

问题描述

编辑:我正在使用 VS Code。

我收到以下警告,因为我的代码带有下划线前缀:

Naming rule violation: Prefix '_' is not expected [MyProject]csharp(IDE1006)

下面是我的代码

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

以下是我的 .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 = _

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

<Project>
  <PropertyGroup>
    <Features>strict</Features>
    <WarningLevel>9999</WarningLevel>
  </PropertyGroup>
</Project>

我正在寻找一种解决方案,在该解决方案中,我可以尽可能严格地保持 C# 的编译器,并且我可以通过允许或最好强制它们(私有字段没有 下划线会收到警告)。

解决方法

我在研究了 Microsoft 的文档后终于想通了here.

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

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

以下是我的新 .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

非常感谢所有帮助过的人,我希望这能帮助到那里的人。

,

在 Visual Studio 中,您可以通过转到选项来执行此操作,然后执行以下步骤:

  1. 转到 C# 下的“命名”
  2. 点击“管理命名样式”
  3. 点击 + 号
  4. 填写逻辑名称
  5. 用 _ 填充“必需的前缀”
  6. 选择“Camel Case Name”作为大写
  7. 点击确定
  8. 点击确定
  9. 点击 + 号
  10. 选择“私有或内部字段”(如果您只想要私有,则需要创建自定义规范)作为规范
  11. 选择您的自定义命名风格作为命名风格
  12. 选择警告作为严重性

请记住,这些设置将被 .editorconfig 覆盖