提问人:Floating Sunfish 提问时间:7/6/2021 最后编辑:Floating Sunfish 更新时间:7/8/2021 访问量:3474
EditorConfig:允许或强制私有字段以下划线开头
EditorConfig: Allow or Enforce Private Fields to Begin with An Underscore
问:
编辑:我正在使用 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 = _
我也在发布我的文件,以防万一它与我上面的文件冲突。
我将其设置为尽可能严格,以便可以修复(或根据需要禁止显示)更严格的 C# 编译器会引发的所有警告:Directory.Build.props
.editorconfig
<Project>
<PropertyGroup>
<Features>strict</Features>
<WarningLevel>9999</WarningLevel>
</PropertyGroup>
</Project>
我正在寻找一种解决方案,我可以使 C# 的编译器尽可能严格,并且可以在私有字段前面加上下划线,方法是允许它们或最好强制执行它们(没有下划线的私有字段会收到警告)。
答:
4赞
Ids van der Zee
7/6/2021
#1
在 Visual Studio 中,可以通过转到“选项”来执行此操作,然后执行以下步骤:
- 转到 C 下的“命名”#
- 点击“管理命名样式”
- 单击 + 号
- 填写逻辑名称
- 将“必需前缀”填写为 _
- 选择“Camel Case Name”进行大写
- 单击“确定”
- 单击“确定”
- 单击 + 号
- 选择“私有或内部字段”(如果您只想私有,则需要创建自定义规范)作为规范
- 选择自定义命名样式作为命名样式
- 选择“警告”作为严重性
请记住,这些设置将被 .editorconfig 覆盖
评论
0赞
Floating Sunfish
7/7/2021
很抱歉,因为我忘了提到我正在使用 VS Code。我已经编辑了 OP。有没有办法为自己做同样的事情?.editorconfig
1赞
Ids van der Zee
7/7/2021
应该可以得到相同的结果,但我不确定如何。.editorconfig
0赞
Floating Sunfish
7/9/2021
我终于想通了!在下面发布了一个答案,并想感谢您鼓励我,即使只有一个文件,这确实是可能的。:).editorconfig
16赞
Floating Sunfish
7/8/2021
#2
在这里研究了 Microsoft 的文档后,我终于弄清楚了。
显然,条目的中间部分是一个标识符,可以设置为我们想要的任何内容。
我创建了一个新规则,要求私有字段以下划线开头,并且采用驼峰大小写。
下面是我的新文件:.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
非常感谢所有帮助过的人,我希望这对那里的某人有所帮助。
评论
1赞
Chris W
4/29/2022
这也会对 和 字段产生警告。static
const
下一个:无法禁止在导入调用期间执行的警告
评论