mcpField
D
dotnet-editorconfig

dotnet-editorconfig

github.com/wshaddix开发8669 次安装35 周前更新
代码仓库

关于 dotnet-editorconfig

面向 .NET 开发者的 Roslyn 代码分析与风格规则配置指南,介绍如何使用 `.editorconfig` 和 `.globalconfig`。涵盖规则严重级别、配置优先级及跨项目的构建强制检查。

主要功能

  1. 01配置 IDE 与 CA 规则
  2. 02规则严重级别与优先级
  3. 03AnalysisLevel 与构建强制检查
  4. 04分层 EditorConfig 设置
  5. 05全局 AnalyzerConfig 指南

适用场景

  1. 01在仓库中统一代码分析规则
  2. 02在 CI 构建中强制执行风格诊断
  3. 03按目录调整分析器严重级别
  4. 04在多个项目间共享分析器设置

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/wshaddix/dotnet-skills --skill dotnet-editorconfig

安装后在 Claude Code 中输入/dotnet-editorconfig确认已加载。

详细介绍

dotnet-editorconfig

通过 .editorconfig 和全局 AnalyzerConfig 文件配置 .NET 代码分析规则的综合指南。涵盖代码样式规则(IDE*)、代码质量规则(CA*)、严重级别、AnalysisLevel、EnforceCodeStyleInBuild、目录层级优先级以及 .globalconfig 文件。

**范围边界:**本技能介绍分析器规则的配置与调整。如需向项目添加分析器包,请参阅 [skill:dotnet-add-analyzers]。如需编写自定义分析器,请参阅 [skill:dotnet-roslyn-analyzers]。如需了解项目级构建配置(Directory.Build.props、解决方案布局),请参阅 [skill:dotnet-project-structure]。

交叉引用:[skill:dotnet-add-analyzers] 介绍如何添加分析器包和设置 AnalysisLevel;[skill:dotnet-roslyn-analyzers] 介绍如何编写自定义分析器;[skill:dotnet-project-structure] 介绍 Directory.Build.props 和解决方案布局;[skill:dotnet-csharp-coding-standards] 介绍由 EditorConfig 规则强制执行的命名和格式约定。


EditorConfig 概览

.editorconfig 是用于控制 .NET 项目中代码样式和分析规则行为的标准配置文件。.NET 编译器(Roslyn)会读取 .editorconfig 来确定:

  • 代码样式偏好——命名、格式、表达式级模式(IDE* 规则)
  • 代码质量规则严重级别——抑制、降低或提高 CA* 和 IDE* 诊断的严重级别
  • 格式规则——缩进、空格、换行
目录层级与优先级

EditorConfig 文件按层级应用。编译器会从源文件所在位置向上搜索到文件系统根目录,并合并找到的每个 .editorconfig 中的设置。距离最近的文件优先——src/MyApp/.editorconfig 中的设置会覆盖仓库根目录 .editorconfig 中的同名设置。

repo-root/
  .editorconfig              # Shared baseline (root = true)
  src/
    .editorconfig            # Overrides for production code
    MyApp.Api/
      .editorconfig          # API-specific overrides (if needed)
  tests/
    .editorconfig            # Relaxed rules for test projects

在最顶层的文件中设置 root = true,即可停止向上遍历。否则,编辑器会继续越过仓库根目录,读取用户或系统级别的 EditorConfig 文件,从而导致行为不可复现。

# repo-root/.editorconfig
root = true

[*.cs]
indent_style = space
indent_size = 4
文件 Glob 模式

EditorConfig 节使用 glob 模式,将设置限定到特定文件:

模式匹配对象
[*.cs]所有 C# 文件
[*.{cs,vb}]C# 和 Visual Basic 文件
[**/test/**/*.cs]任意 test 目录下的 C# 文件
[Program.cs]完全匹配的文件名

代码样式规则(IDE*)

IDE 规则用于控制由 Roslyn 编译器和 IDE 强制执行的代码样式偏好。可通过 dotnet_style_*、csharp_style_* 和 dotnet_diagnostic.IDE*.severity 条目进行配置。

主要 IDE 规则类别
范围类别示例
IDE0001-IDE0009简化IDE0001(简化名称)、IDE0003(移除 this. 限定)、IDE0005(移除不必要的 using)
IDE0010-IDE0039表达式偏好IDE0016(throw 表达式)、IDE0017(对象初始值设定项)、IDE0018(内联变量)、IDE0028(集合初始值设定项)、IDE0034(简化 default)、IDE0039(使用局部函数)
IDE0040-IDE0069修饰符和访问性偏好IDE0040(添加可访问性修饰符)、IDE0044(添加 readonly)、IDE0062(将局部函数设为 static)
IDE0070-IDE0090+模式匹配和现代语法IDE0071(简化插值)、IDE0078(使用模式匹配)、IDE0090(简化 new 表达式)
IDE0100-IDE0180其他简化IDE0130(命名空间与文件夹匹配)、IDE0160/IDE0161(块范围与文件范围命名空间)
IDE0200-IDE0260Lambda 和方法偏好IDE0200(移除不必要的 Lambda)、IDE0230(使用 UTF-8 字符串字面量)
IDE1005-IDE1006命名规则IDE1006(命名规则冲突)
配置代码样式偏好
[*.cs]
# Expression-level preferences
csharp_style_expression_bodied_methods = when_on_single_line:suggestion
csharp_style_expression_bodied_properties = true:suggestion
csharp_style_expression_bodied_constructors = false:silent

# Pattern matching
csharp_style_prefer_pattern_matching = true:suggestion
csharp_style_prefer_switch_expression = true:suggestion
csharp_style_prefer_not_pattern = true:suggestion

# Null checking
csharp_style_prefer_null_check_over_type_check = true:suggestion
dotnet_style_coalesce_expression = true:suggestion
dotnet_style_null_propagation = true:suggestion

# var preferences
csharp_style_var_for_built_in_types = false:suggestion
csharp_style_var_when_type_is_apparent = true:suggestion
csharp_style_var_elsewhere = false:suggestion

# Namespace style (.NET 6+)
csharp_style_namespace_declarations = file_scoped:warning

# Using directives
csharp_using_directive_placement = outside_namespace:warning
dotnet_sort_system_directives_first = true
通过 dotnet_diagnostic 配置 IDE 规则严重级别

可为每条 IDE 规则单独设置严重级别:

[*.cs]
# Enforce removal of unnecessary usings as a build warning
dotnet_diagnostic.IDE0005.severity = warning

# Enforce file-scoped namespaces as a build error
dotnet_diagnostic.IDE0161.severity = error

# Demote new-expression simplification to suggestion
dotnet_diagnostic.IDE0090.severity = suggestion

# Disable this. qualification rule entirely
dotnet_diagnostic.IDE0003.severity = none

代码质量规则(CA*)

CA 规则用于检测设计、性能、安全性、可靠性和使用方面的问题。它们随 .NET SDK 一同提供,并由 AnalysisLevel 控制。有关完整的 CA 规则类别表和 AnalysisLevel 设置指南,请参阅 [skill:dotnet-add-analyzers]。

CA 的主要类别包括:设计(CA1000s)、全球化(CA1300s)、互操作性(CA1400s)、可维护性(CA1500s)、命名(CA1700s)、性能(CA1800s)、可靠性(CA2000s)、安全性(CA2100s、CA3xxx、CA5xxx)和使用(CA2200s)。

CA 规则严重性配置
[*.cs]
# Suppress rules not applicable to your project type
dotnet_diagnostic.CA1062.severity = none          # Nullable handles parameter validation
dotnet_diagnostic.CA2007.severity = none          # ConfigureAwait not needed in ASP.NET Core apps

# Escalate important rules
dotnet_diagnostic.CA1822.severity = warning       # Mark members as static
dotnet_diagnostic.CA1848.severity = warning       # Use LoggerMessage delegates
dotnet_diagnostic.CA2016.severity = warning       # Forward CancellationToken

# Error-level for security rules
dotnet_diagnostic.CA2100.severity = error         # SQL injection review
dotnet_diagnostic.CA5350.severity = error         # Weak cryptographic algorithms

严重性级别

五种严重性级别控制诊断的报告方式:

严重性构建输出IDE 波浪线错误列表是否导致构建失败(TreatWarningsAsErrors)
error是(错误)红色错误选项卡始终
warning是(警告)绿色警告选项卡是(启用 TreatWarningsAsErrors 时)
suggestion否灰色点消息选项卡否
silent否否否否(可用代码修复,但不会显示在构建输出或错误列表中)
none否否否否(规则完全禁用)
批量严重性配置

为整个类别设置默认严重性:

[*.cs]
# Set all design rules to warning
dotnet_analyzer_diagnostic.category-Design.severity = warning

# Set all performance rules to error
dotnet_analyzer_diagnostic.category-Performance.severity = error

# Set all naming rules to suggestion
dotnet_analyzer_diagnostic.category-Naming.severity = suggestion

dotnet_analyzer_diagnostic.category-{Category}.severity 的有效类别名称包括:Design、Documentation、Globalization、Interoperability、Maintainability、Naming、Performance、SingleFile、Reliability、Security、Usage。IDE* 规则不参与类别级批量配置——请通过 dotnet_diagnostic.IDE*.severity 单独配置。

单条规则的设置会覆盖类别级设置。类别级设置会覆盖 AnalysisLevel 默认值。

优先级顺序(从高到低):

  1. 单条规则:dotnet_diagnostic.CA1822.severity = error
  2. 单个类别:dotnet_analyzer_diagnostic.category-Performance.severity = warning
  3. AnalysisLevel 基准(在 MSBuild 属性中设置)

AnalysisLevel 和 EnforceCodeStyleInBuild

AnalysisLevel 控制启用哪些内置 CA 规则及其默认严重性。取值范围从 latest(默认,仅检查正确性)到 latest-all(所有规则)。固定使用特定的 .NET SDK 主版本(例如 8-all、10-all),可在 SDK 升级期间锁定规则集。使用 preview-all 可获得最广泛的覆盖范围,其中包括实验性规则。有关完整的 AnalysisLevel 取值表和设置指南,请参阅 [skill:dotnet-add-analyzers]。

EnforceCodeStyleInBuild

默认情况下,IDE* 规则仅在 IDE 中运行,不会在 dotnet build 期间运行。启用构建时强制执行:

<PropertyGroup>
  <EnforceCodeStyleInBuild>true</EnforceCodeStyleInBuild>
</PropertyGroup>

这对于在 CI 中强制执行至关重要——如果不启用此项,即使 .editorconfig 将代码样式违规配置为警告或错误,这些违规仍可能漏过检查。与 TreatWarningsAsErrors 配合使用可严格强制执行:

<PropertyGroup>
  <AnalysisLevel>latest-all</AnalysisLevel>
  <EnforceCodeStyleInBuild>true</EnforceCodeStyleInBuild>
  <TreatWarningsAsErrors>true</TreatWarningsAsErrors>
</PropertyGroup>

全局 AnalyzerConfig 文件(.globalconfig)

全局 AnalyzerConfig 文件(.globalconfig)为分析器配置提供了 .editorconfig 之外的另一种选择。它们会全局应用于编译中的所有文件,无需按目录相对位置放置。

何时使用 .globalconfig,而非 .editorconfig
方面.editorconfig.globalconfig
范围相对于目录(文件 glob 区段)整个编译(无文件区段)
层级沿目录向上合并扁平——不遍历目录
IDE 支持完整(格式化、重构、分析)仅分析规则
使用场景按目录配置格式化和分析在多个项目或 NuGet 包之间共享规则配置
.globalconfig 语法
# Filename: .globalconfig (or any name with is_global = true)
is_global = true

# Global level determines priority (higher number = higher priority)
global_level = 100

# Configure rules (same syntax as .editorconfig, without [*.cs] sections)
dotnet_diagnostic.CA1822.severity = warning
dotnet_diagnostic.CA2007.severity = none
dotnet_diagnostic.IDE0005.severity = warning
在项目中包含 .globalconfig

通过 MSBuild GlobalAnalyzerConfigFiles 项引用:


<ItemGroup>
  <GlobalAnalyzerConfigFiles Include="$(MSBuildThisFileDirectory).globalconfig" />
</ItemGroup>

NuGet 分析器包可以在 buildTransitive/ 中附带 .globalconfig 文件,为使用者应用默认严重性。

global_level 优先级

当多个 .globalconfig 文件适用时,global_level 值决定哪个文件优先。值越高,优先级越高。SDK 默认全局配置使用 global_level = -1。用户配置应使用 global_level = 0 或更高的值(省略时默认为 0)。NuGet 随附的配置使用负值,以便用户覆盖。

完整优先级顺序(从高到低):

  1. 按规则设置的 .editorconfig 条目
  2. 按类别设置的 .editorconfig 条目
  3. global_level 最高的 .globalconfig
  4. global_level 较低的 .globalconfig
  5. SDK 默认配置(AnalysisLevel)

命名规则(IDE1006)

EditorConfig 支持自定义命名规则,可在生成时强制执行命名约定(需启用 EnforceCodeStyleInBuild):

[*.cs]
# Define symbol groups
dotnet_naming_symbols.public_members.applicable_kinds = property, method, field, event
dotnet_naming_symbols.public_members.applicable_accessibilities = public

dotnet_naming_symbols.private_fields.applicable_kinds = field
dotnet_naming_symbols.private_fields.applicable_accessibilities = private

dotnet_naming_symbols.interfaces.applicable_kinds = interface

# Define naming styles
dotnet_naming_style.pascal_case.capitalization = pascal_case

dotnet_naming_style.underscore_prefix.capitalization = camel_case
dotnet_naming_style.underscore_prefix.required_prefix = _

dotnet_naming_style.interface_prefix.capitalization = pascal_case
dotnet_naming_style.interface_prefix.required_prefix = I

# Bind rules (lower number = higher priority)
dotnet_naming_rule.interfaces_must_start_with_i.symbols = interfaces
dotnet_naming_rule.interfaces_must_start_with_i.style = interface_prefix
dotnet_naming_rule.interfaces_must_start_with_i.severity = warning

dotnet_naming_rule.public_members_pascal_case.symbols = public_members
dotnet_naming_rule.public_members_pascal_case.style = pascal_case
dotnet_naming_rule.public_members_pascal_case.severity = warning

dotnet_naming_rule.private_fields_underscore.symbols = private_fields
dotnet_naming_rule.private_fields_underscore.style = underscore_prefix
dotnet_naming_rule.private_fields_underscore.severity = warning

常用配置模板

推荐的基准配置(.editorconfig)
root = true

[*]
indent_style = space
indent_size = 4
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true

[*.cs]
# Namespace and using preferences
csharp_style_namespace_declarations = file_scoped:warning
csharp_using_directive_placement = outside_namespace:warning
dotnet_sort_system_directives_first = true

# Code style enforcement in build
dotnet_diagnostic.IDE0005.severity = warning
dotnet_diagnostic.IDE0161.severity = warning
dotnet_diagnostic.IDE0090.severity = suggestion

# CA rule adjustments
dotnet_diagnostic.CA1848.severity = warning
dotnet_diagnostic.CA2016.severity = warning
测试项目覆盖配置(tests/.editorconfig)

在 tests/ 目录中放置单独的 .editorconfig,以放宽与测试可读性冲突的规则。如需了解常见的按项目类型抑制模式(ASP.NET Core 应用、库、测试项目),请参阅 [skill:dotnet-add-analyzers]。

[*.cs]
# Relax rules for test readability
dotnet_diagnostic.CA1707.severity = none          # Allow underscores in test names
dotnet_diagnostic.CA1822.severity = none          # Test methods often not static
dotnet_diagnostic.IDE0058.severity = none         # Expression value is never used

生成代码配置

源生成器和脚手架工具生成的代码常会触发 IDE/CA 警告。使用 generated_code = true 设置或文件 glob 模式,可对生成的文件禁用分析:

# Suppress warnings in generated code files
[*.g.cs]
generated_code = true

[*.generated.cs]
generated_code = true

设置 generated_code = true 后,Roslyn 会将文件视为生成代码,并应用各个分析器配置的 GeneratedCodeAnalysisFlags(大多数分析器默认跳过生成代码)。使用源生成器时,这一点尤其重要——请参阅 [skill:dotnet-csharp-source-generators]。


参考资料

评论

支持 Markdown