code-analysis
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
Chinese.NET Code Analysis
.NET 代码分析
Trigger On
触发场景
- the repo wants first-party .NET analyzers
- CI should fail on analyzer warnings
- the team needs or
AnalysisLevelguidanceAnalysisMode - the repo needs a gradual Roslyn warning promotion strategy
- 仓库需要官方.NET分析器
- CI需因分析器警告而失败
- 团队需要或
AnalysisLevel相关指导AnalysisMode - 仓库需要Roslyn警告逐步升级策略
Do Not Use For
不适用场景
- third-party analyzer selection by itself
- formatting-only work
- 仅选择第三方分析器
- 仅做格式调整操作
Inputs
输入项
- the nearest
AGENTS.md - project files or
Directory.Build.props - current analyzer severity policy
- 最近的文件
AGENTS.md - 项目文件或
Directory.Build.props - 当前分析器严重性策略
Hard Rules for AI Agents
AI Agent 硬性规则
Non-negotiable. Violating these undermines the user's explicit intent.
- Never disable or remove or
TreatWarningsAsErrorsif the project has set them. Do not comment them out, set toWarningsAsErrors, wrap in a condition, or addfalseto make the build pass.<TreatWarningsAsErrors>false</TreatWarningsAsErrors> - Never add or
<NoWarn>for warnings the user chose to treat as errors, unless the user explicitly approves the suppression.#pragma warning disable - Never silently downgrade severity in (e.g.
.editorconfigtoerrororwarning) to make a build succeed.none - If warnings-as-errors breaks the build — fix the code. If the fix is too large, ask the user whether to defer that warning ID.
- If warning volume is too large to fix in one pass — report count and categories to the user and ask which to tackle first. Do not unilaterally disable the policy.
不可协商。违反这些规则会违背用户的明确意图。
- 如果项目已设置或
TreatWarningsAsErrors,绝不能禁用或移除它们。不要注释掉、设为WarningsAsErrors、添加条件包裹,或添加false来让构建通过。<TreatWarningsAsErrors>false</TreatWarningsAsErrors> - 绝不能为用户选择视为错误的警告添加或
<NoWarn>,除非用户明确批准抑制该警告。#pragma warning disable - 绝不能在中悄悄降低严重性(例如从
.editorconfig改为error或warning)来让构建成功。none - 如果“将警告视为错误”导致构建失败——修复代码。如果修复工作量太大,请询问用户是否推迟处理该警告ID。
- 如果警告数量过多,无法一次性修复——向用户报告警告数量和类别,询问优先处理哪些。不要单方面禁用该策略。
Workflow
工作流程
mermaid
flowchart TD
A[Start] --> B{New or legacy project?}
B -->|New| C[TreatWarningsAsErrors=true immediately]
B -->|Legacy| D[dotnet build, count warnings by ID]
D --> E{"< 30 warnings?"}
E -->|Yes| F[Fix all, then enable TreatWarningsAsErrors]
E -->|No| G[Report counts to user, ask which batch first]
G --> H[Add selected IDs to WarningsAsErrors]
H --> I[Fix that batch, verify build]
I --> J{More batches?}
J -->|Yes| G
J -->|No| F
C --> K[Set AnalysisLevel latest-recommended]
F --> K
K --> L[Promote security CA3xxx/CA5xxx to error in .editorconfig]
L --> M[Validate: build + CI green]- Start with SDK analyzers before third-party packages.
- Detect project maturity: new or existing/legacy.
- Enable ,
EnableNETAnalyzers,AnalysisLevelinAnalysisMode.Directory.Build.props - Apply the right warning promotion strategy (see below).
- Per-rule severity goes in repo-root .
.editorconfig - is the analyzer gate in CI.
dotnet build
mermaid
flowchart TD
A[Start] --> B{New or legacy project?}
B -->|New| C[TreatWarningsAsErrors=true immediately]
B -->|Legacy| D[dotnet build, count warnings by ID]
D --> E{"< 30 warnings?"}
E -->|Yes| F[Fix all, then enable TreatWarningsAsErrors]
E -->|No| G[Report counts to user, ask which batch first]
G --> H[Add selected IDs to WarningsAsErrors]
H --> I[Fix that batch, verify build]
I --> J{More batches?}
J -->|Yes| G
J -->|No| F
C --> K[Set AnalysisLevel latest-recommended]
F --> K
K --> L[Promote security CA3xxx/CA5xxx to error in .editorconfig]
L --> M[Validate: build + CI green]- 优先使用SDK分析器,再考虑第三方包。
- 检测项目成熟度:新项目还是已有/遗留项目。
- 在中启用
Directory.Build.props、EnableNETAnalyzers、AnalysisLevel。AnalysisMode - 应用合适的警告升级策略(见下文)。
- 每条规则的严重性设置在仓库根目录的中。
.editorconfig - CI中使用作为分析器检查关卡。
dotnet build
Warning Promotion Strategy
警告升级策略
New Projects
新项目
Set these in immediately:
Directory.Build.props- = true
TreatWarningsAsErrors - = latest-recommended
AnalysisLevel - Security category = error in
.editorconfig
Fix all warnings before merging.
立即在中设置以下内容:
Directory.Build.props- = true
TreatWarningsAsErrors - = latest-recommended
AnalysisLevel - 在中将安全类别设为error
.editorconfig
合并代码前修复所有警告。
Legacy Projects — Gradual Promotion
遗留项目——逐步升级
Blanket on a legacy codebase produces hundreds/thousands of errors. An agent cannot fix them all at once — context floods, fix quality drops. Promote in batches.
TreatWarningsAsErrors对遗留代码库全面启用会产生成百上千个错误。Agent无法一次性全部修复——上下文过载,修复质量下降。应分批升级。
TreatWarningsAsErrorsPhase 1: Trivial Hygiene (start here)
阶段1:基础代码清理(从此开始)
Mechanical fixes, lowest effort:
- CS8019 — unnecessary using directive (remove it)
- CS0219 — variable assigned but never used (remove it)
- CS0168 — variable declared but never used (remove it)
- CS1591 — missing XML comment for public member (add comment or disable for internal code)
- CS0612 — obsolete member used, no message (replace with non-obsolete API)
- CS0618 — obsolete member used, with message (follow migration guidance)
Add to : . Fix all, then Phase 2.
WarningsAsErrorsCS8019;CS0219;CS0168机械性修复,最低工作量:
- CS8019 — 不必要的using指令(移除)
- CS0219 — 变量已赋值但从未使用(移除)
- CS0168 — 变量已声明但从未使用(移除)
- CS1591 — 公共成员缺少XML注释(添加注释或对内部代码禁用该规则)
- CS0612 — 使用了已过时成员,无提示信息(替换为非过时API)
- CS0618 — 使用了已过时成员,有提示信息(遵循迁移指南)
将以下ID添加到:。修复所有相关问题后进入阶段2。
WarningsAsErrorsCS8019;CS0219;CS0168Phase 2: Code Quality (ask user which categories)
阶段2:代码质量(询问用户选择哪些类别)
- CA2000 — dispose objects before losing scope (Reliability)
- CA1062 — validate public method arguments (Design)
- CA1822 — mark members as static (Performance)
- CA1860 — avoid Enumerable.Any() for length check (Performance)
- CA1861 — avoid constant arrays as arguments (Performance)
- CA2007 — consider calling ConfigureAwait (Reliability)
- CS8600–CS8610 — nullable reference type warnings (Nullability)
Ask: "Which categories next — Nullability, Performance, or Reliability?" Add selected IDs to , fix, repeat.
WarningsAsErrors- CA2000 — 失去对象作用域前释放对象(可靠性)
- CA1062 — 验证公共方法参数(设计)
- CA1822 — 将成员标记为static(性能)
- CA1860 — 避免使用Enumerable.Any()检查长度(性能)
- CA1861 — 避免将常量数组作为参数(性能)
- CA2007 — 考虑调用ConfigureAwait(可靠性)
- CS8600–CS8610 — 可空引用类型警告(空值安全性)
询问:“接下来处理哪个类别——空值安全性、性能还是可靠性?”将选中的ID添加到,修复后重复该步骤。
WarningsAsErrorsPhase 3: Security (always promote early)
阶段3:安全(尽早升级)
Set in regardless of project maturity:
.editorconfigeditorconfig
[*.cs]
dotnet_analyzer_diagnostic.category-Security.severity = errorCovers CA3001 (SQL injection), CA3002 (XSS), CA3003 (path injection), CA3075 (insecure DTD), CA5350/CA5351 (weak crypto), CA5394 (insecure randomness).
无论项目成熟度如何,在中设置:
.editorconfigeditorconfig
[*.cs]
dotnet_analyzer_diagnostic.category-Security.severity = error涵盖CA3001(SQL注入)、CA3002(XSS)、CA3003(路径注入)、CA3075(不安全DTD)、CA5350/CA5351(弱加密)、CA5394(不安全随机数)。
Phase 4: Full Coverage
阶段4:全面覆盖
Once all batches pass, transition to:
xml
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
<WarningsNotAsErrors>CA1707</WarningsNotAsErrors> <!-- explicit exceptions only -->所有批次通过后,过渡到:
xml
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
<WarningsNotAsErrors>CA1707</WarningsNotAsErrors> <!-- 仅显式例外情况 -->Interaction Protocol (legacy codebases)
遗留代码库交互协议
- Run , count warnings by ID.
dotnet build - Report summary: "Found 47 CS8019, 23 CA1822, 12 CA2000, 8 CS8600."
- Ask which batch to tackle. Recommend starting with Phase 1.
- Fix selected batch, verify build.
- Add those IDs to .
WarningsAsErrors - Report back, ask about next batch.
Never skip the ask step. The user decides the pace.
- 运行,按ID统计警告数量。
dotnet build - 报告摘要:“发现47个CS8019、23个CA1822、12个CA2000、8个CS8600。”
- 询问优先处理哪个批次。建议从阶段1开始。
- 修复选中的批次,验证构建。
- 将这些ID添加到。
WarningsAsErrors - 反馈结果,询问下一个批次。
绝不能跳过询问步骤。用户决定进度。
Bootstrap When Missing
缺失时的初始化配置
- Detect current state:
dotnet --inforg -n "EnableNETAnalyzers|AnalysisLevel|AnalysisMode|TreatWarningsAsErrors|WarningsAsErrors" -g '*.csproj' -g 'Directory.Build.*' .- — count warnings by ID
dotnet build SOLUTION_OR_PROJECT 2>&1
- Classify: new (few/zero warnings) vs legacy (many warnings).
- Enable ,
EnableNETAnalyzers,AnalysisLevelin MSBuild config.AnalysisMode - Apply promotion strategy matching project maturity.
- Per-rule severity in repo-root .
.editorconfig - Run , return
dotnet buildorstatus: configured.status: improved - If repo defers analyzer policy to another build layer, return .
status: not_applicable
- 检测当前状态:
dotnet --inforg -n "EnableNETAnalyzers|AnalysisLevel|AnalysisMode|TreatWarningsAsErrors|WarningsAsErrors" -g '*.csproj' -g 'Directory.Build.*' .- — 按ID统计警告数量
dotnet build SOLUTION_OR_PROJECT 2>&1
- 分类:新项目(少量/无警告) vs 遗留项目(大量警告)。
- 在MSBuild配置中启用、
EnableNETAnalyzers、AnalysisLevel。AnalysisMode - 应用与项目成熟度匹配的升级策略。
- 在仓库根目录的中设置每条规则的严重性。
.editorconfig - 运行,返回
dotnet build或status: configured。status: improved - 如果仓库将分析器策略委托给其他构建层,返回。
status: not_applicable
Deliver
交付成果
- explicit, reviewable first-party analyzer policy
- build-time analyzer execution for CI
- warning promotion plan matching project maturity
- 明确的、可审核的官方分析器策略
- CI中执行构建时分析器检查
- 与项目成熟度匹配的警告升级计划
Validate
验证
- analyzer behavior driven by repo config, not IDE defaults
- CI reproduces same warnings/errors locally
- no ,
TreatWarningsAsErrors, or severity settings removed/weakened without user approvalWarningsAsErrors - promoted warnings produce build errors, not just IDE hints
- 分析器行为由仓库配置驱动,而非IDE默认设置
- CI中的警告/错误与本地一致
- 未经用户批准,不得移除/弱化、
TreatWarningsAsErrors或严重性设置WarningsAsErrors - 升级后的警告会导致构建错误,而非仅IDE提示
Ralph Loop
Ralph 循环
- Plan: analyze state, define target, constraints, risks, execution plan, validation steps.
- Execute one step, produce concrete delta.
- Review result, capture findings.
- Apply fixes in small batches, rerun checks.
- Update plan after each iteration.
- Repeat until acceptable or only explicit exceptions remain.
- Missing dependency: bootstrap or return .
status: not_applicable
- 规划:分析状态,定义目标、约束、风险、执行计划和验证步骤。
- 执行一步操作,产生具体变更。
- 审查结果,记录发现。
- 小批量应用修复,重新运行检查。
- 每次迭代后更新计划。
- 重复直到达到可接受状态或仅剩下显式例外情况。
- 缺失依赖项:初始化配置或返回。
status: not_applicable
Required Result Format
要求的结果格式
- :
status|complete|clean|improved|configured|not_applicableblocked - : concise plan and current step
plan - : concrete changes
actions_taken - : final skills run or skipped with reasons
validation_skills - : commands, checks, or review evidence
verification - : unresolved items or
remainingnone
- :
status|complete|clean|improved|configured|not_applicableblocked - : 简洁的计划和当前步骤
plan - : 具体变更内容
actions_taken - : 最终运行的技能或跳过的原因
validation_skills - : 命令、检查或审查证据
verification - : 未解决项或
remainingnone
Load References
参考资料
- references/rules.md
- references/config.md
- references/code-analysis.md
- references/rules.md
- references/config.md
- references/code-analysis.md
Example Requests
请求示例
- "Turn on built-in .NET analyzers."
- "Make analyzer warnings fail the build."
- "Set the right AnalysisLevel for this repo."
- "Start treating unused usings and unused variables as errors."
- "Help me gradually promote Roslyn warnings in my legacy project."
- "Which warnings should I promote to errors next?"
- "启用内置的.NET分析器。"
- "让分析器警告导致构建失败。"
- "为这个仓库设置合适的AnalysisLevel。"
- "开始将未使用的using和未使用的变量视为错误。"
- "帮助我逐步升级遗留项目中的Roslyn警告。"
- "接下来我应该将哪些警告升级为错误?"