C#/.NET 代码安全重构
csharp-refactoring
在不改变行为的前提下安全地重构 C#/.NET 代码:重命名、移动、提取、内联、合并、整合、去重、拆分或现代化改造,涵盖分部声明或生成的声明、公共 API、序列化和反射名称、友元程序集、条件编译以及多目标项目。当请求要求重构,或把某个功能、错误修复、升级或公共可空性变更称为重构时使用;此时必须把会改变行为的部分分离出来或予以拒绝。不适用于普通的功能或错误修复、独立的框架或包升级、添加测试,或仅涉及格式的工作。
- License 许可
- MIT
- 最近更新
- 2026-11-14
- Stars
- ★ 1
- Forks
- 1
01 前言 Front Matter
- name
- csharp-refactoring
- license
- MIT
- description
- Safely refactors C#/.NET code without changing behavior: rename, move, extract, inline, merge, consolidate, deduplicate, split, or modernize, including partial or generated declarations, public APIs, serialization and reflection names, friend assemblies, conditional compilation, and multi-targeted projects. Use when a request asks for a refactor, or calls a feature, bug fix, upgrade, or public nullability change a refactor and the behavior-changing part must be separated or declined. Not for ordinary feature or bug fixes, standalone framework or package upgrades, adding tests, or formatting-only work.
02 资源文件 3
- 许可证LICENSE1.1 KB
- 其他NOTICE1.1 KB
- 参考文档references/operation-catalog.md2.9 KB
03 SKILL.md 正文
<!-- cratis-ai-managed: skills/csharp-refactoring/SKILL.md -->
<!-- Modified by Cratis from dotnet's original (MIT): frontmatter, applicability, navigation and the changes listed in NOTICE. Upstream: https://github.com/dotnet/skills (plugins/dotnet/skills/csharp-refactoring/SKILL.md; see NOTICE) -->
C# Refactoring (behavior-preserving)
Cratis rules in .cratis/ai/rules/ (including csharp.md, specs.csharp.md, and orleans.md) and the cratis-* skills win where they differ.
A refactor changes structure, never observable behavior. Do the edit with binding-aware tools, then confirm behavior held with a build + the relevant tests. Keep the effort proportional to the change: a one-line local rename does not need the ceremony a public multi-targeted change does.
Mandatory gate: classify before validation or editing
Read only enough repository context to classify each requested operation. Do this before restoring, building, or making an edit. Classification precedence is:
- If the request explicitly asks for at least one separable behavior-preserving operation, complete that structural work and defer only the behavior-changing or contract-changing operations. Do not invent or infer structural work to avoid the stop response.
- If the structural and behavior-changing parts cannot be separated, use the whole-request stop response and state why they are inseparable.
- Otherwise, use the whole-request stop response only when every requested operation is outside behavior-preserving refactoring.
For a whole request that is outside behavior-preserving refactoring:
- State:
Not a behavior-preserving refactor: <specific reason>. - State:
No files changed. - State:
Next workflow: <workflow>.Then stop. Do not add manual implementation steps, alternatives, an offer to proceed without the workflow, or a follow-up question — even when that workflow is unavailable.
| Requested as a "refactor" | Classification and action |
|---|---|
| Framework or NuGet version change | Upgrade. Do not edit or validate the upgrade here; hand off to the repository's upgrade workflow. |
| New capability, flag, endpoint, tier, or behavior | Feature. Do not implement it here; hand off to the repository's feature workflow. |
| Threshold, rate, output, or bug-result change | Behavior change. Defer it and hand off to the repository's bug-fix or behavior-change workflow; still complete any clearly separable structural operation. |
| Tighten or loosen a shipped/public nullable annotation | Source-contract change. Leave the declaration and API record unchanged; hand off to the repository's API-contract workflow. |
For a mixed request, never stop after classification. Perform the separable structural operation,
explicitly defer the behavior/contract change, and never state No files changed. after completing
structural work. Never modify tests to make an unauthorized behavior change appear preserved.
Work only in the current workspace
Use the current agent workspace as the boundary. If it is a Git checkout, resolve its repository root
(git rev-parse --show-toplevel) and stay inside it. If Git metadata is absent, treat the current working
directory and its subdirectories as the boundary, and use a solution or project named in the request
inside it; Git is not a prerequisite for a refactor. Resolve prompt-provided relative paths inside that
boundary.
Search and edit only that workspace. Never use filesystem-wide search or select a similarly named clone, another worktree, build output, or unrelated temporary directory because a file also exists there. If a named path is absent, stop and report the mismatch instead of guessing another workspace. If a tool rejects an in-workspace path for a mechanical reason such as path form or unsupported tool root, retry through another in-workspace mechanism. If the rejection is a permission or policy denial, report it instead of working around it. Never search outside the boundary.
Rename / move by bindings, not text
The #1 way a "rename" silently corrupts code is editing textual matches (comments, strings, unrelated
overloads) instead of real bindings. Find every binding reference first, then edit semantically. Use
the strongest tool available: an IDE/Roslyn workspace refactoring, then the C# LSP the
dotnet plugin declares
(findReferences, goToDefinition, incomingCalls, rename code action), then analyzer code-fixes /
Roslynator, then compiler-validated edits (edit the true bindings, rebuild, let the compiler flag misses).
Plain find/replace only when scope is provably tiny and every hit is verified. Include every partial
declaration, and edit the generator input, never generated (*.g.cs) output.
For the operation → Roslyn-provider mapping and representative PRs, see references/operation-catalog.md.
Consolidate toward the existing source of truth
When de-duplicating, preserve the ownership direction stated by the code or request. If B duplicates
an implementation already owned by A, keep A canonical and make B delegate to it; do not invert
the dependency merely because either direction compiles. Preserve public compatibility wrappers when
the duplicate surface is shipped, and migrate only in-repo callers that are safe to move.
Decisions that change the edit
Use the first matching row instead of applying the requested operation mechanically:
| Situation | Do | Never |
|---|---|---|
| Inline an internal, unshipped pass-through wrapper | Migrate every binding reference to the target, remove the wrapper, then compile to catch misses. | Keep dead indirection "for compatibility" when no compatibility boundary exists. |
| Inline or remove a shipped/public wrapper | Migrate ordinary in-repo callers, but retain an [Obsolete] forwarding entry point unless the request explicitly authorizes a breaking change. |
Delete a shipped API merely because all current source callers were migrated. |
| Rename a member reached by a string, reflection, DI, or configuration | Rename binding-based callers; preserve the observed external name with a forwarding shim or metadata, and exercise the old-name path. | Rewrite an external/configured name just to make the new source name consistent. |
| Extract duplicated logic whose callers pass different values | Extract the algorithm and pass each caller's existing inputs through unchanged. | Collapse distinct inputs, evaluation order, rounding, or side effects into one caller's version. |
Rename code compiled under #if or multiple TFMs |
Update every source branch and validate each target framework explicitly. | Treat a green default-target build as evidence for unbuilt branches. |
| Merge near-identical types | Parameterize only the values that differ, migrate every construction site, and preserve each old value exactly. If the old types are internal/unshipped and the request says to merge into one type, delete their declarations. | Retain unnecessary aliases, static holders, factories, or wrapper types that leave the requested merge incomplete; introduce a new hierarchy or behavior. |
Preserve contracts beyond C# call sites
Compilation proves binding compatibility, not every external contract. Before renaming or moving a
type/member, check whether its name or metadata is observed by serialization, reflection, dependency
injection, configuration binding, source generators, P/Invoke, or dynamic.
| Boundary | Required decision |
|---|---|
| Serialized/configuration name | Preserve the external name with the repository's existing mechanism (for example, JsonPropertyName) while migrating C# callers; run a focused round-trip or payload test. |
| Public nullable annotation | The mandatory classification gate applies: leave it unchanged and hand off as a source-contract change. |
| Uncovered reflection or runtime lookup | Do not guess that a compile-clean rename is safe. Preserve the observed name or stop and report the unverified runtime boundary. |
Verify proportionally
Confirm behavior is preserved after the edit — scaled to blast radius, not a fixed ceremony:
- Local / private (method-local or
privatemember, one file, single target framework, no public surface, nopartial/generated/#if): skip a separate baseline unless the tree is already suspect. Make the edit, then run the narrowest build and relevant tests once. Let the compiler catch missed references. - Cross-boundary (public/shipped symbol, multi-targeted project,
#if/platform branches, orpartial/generated code): establish a baseline, then run an explicit build and the relevant tests for each target framework after the edit (a test command's implicit build is not separate build evidence; a green default build can hide a break on another TFM), and run the hazards check below.
Use the repo's own build/test workflow when it documents one (README/CONTRIBUTING, build.*, eng/,
global.json, .github/workflows); its instructions win over any generic command.
Typical workflow (one operation)
- Choose one named refactoring operation and keep the step focused on that operation only.
- Find true binding references (
findReferences/goToDefinition/rename) and include allpartialdeclarations. - Establish a baseline first only for a cross-boundary change or a tree not already known green.
- Apply the change via the most semantics-aware tool available; avoid blind find/replace when possible.
- Rebuild and run the relevant tests. If the gate goes red, report the failure and repair or reassess only your edit; never discard unrelated worktree changes.
Otherwise:
dotnet build # 0 errors
dotnet test # stays green; same pass count as before
One operation per step; never mix a refactor and a behavior change in the same step. On red, stop and report the failure; repair only your edit without discarding unrelated worktree changes.
Final response contract
Keep the handoff concise and evidence-based:
- Refactor: name the structural operation and the symbols/files changed.
- Preserved: name the behavior or compatibility boundary and the mechanism that preserved it.
- Validation: report the exact commands and observed result; never claim success after a failed restore, build, target framework, or test run.
- Deferred: for a mixed request, name the behavior/contract change intentionally left undone and its correct next workflow. Omit this line when nothing was deferred.
Cross-boundary hazards (only when it touches a boundary)
If — and only if — the change touches a public symbol, a multi-targeted project, or
partial/generated code, some breaks won't show up as a failing test. Search the repo for the surface
that governs the symbol (don't assume): the public-API gate (PublicAPI.Shipped/Unshipped.txt for
PublicApiAnalyzers, and/or ApiCompat/<EnablePackageValidation> — not interchangeable),
<TargetFrameworks>/#if branches, and InternalsVisibleTo. Moving a public type to another assembly
needs [TypeForwardedTo] in the original assembly; a move within one assembly does not. A public
rename needs an [Obsolete] shim, not a forwarder. For a provably local/private change, skip these
checks.
Stop an in-scope refactor when
- The baseline is already red (you can't prove you preserved behavior).
- The requested structural change would alter a public/shipped API and no compatibility shim or forwarder
can preserve it. Report the boundary. Use the gate's handoff format when no structural work was completed;
after separable work, put the incompatible operation on the
Deferred:line instead. Do not ask to make the breaking change. - Equivalence depends on runtime behavior tests don't cover (reflection, DI, serialization,
dynamic, P/Invoke) — report the unverified boundary instead of claiming behavior was preserved.
Contracts the compiler cannot see in Cratis code
Preserve [EventType] identifiers and type names of persisted events, generated TypeScript proxies of Arc commands/queries, [Alias]/serializer ids in Orleans, and public API of framework packages (semver).
04 同仓库更多 Skills
.NET SIMD 向量化代码
vectorization
设计、实现、优化和审查 .NET 中的 SIMD 代码:使用 TensorPrimitives、Vector64、Vector128、Vector256、Vector512 或硬件内部函数将标量循环向量化,并审查现有 SIMD 代码(包括泛型 Vector 类型)的契约等价性、尾部处理、内存安全性、可移植性、回退方案和实测性能。当正在编写或审查 .NET 循环或 SIMD 例程时使用。不用于与 SIMD 无关的性能工作。
MSBuild自定义目标编写
target-authoring
编写自定义 MSBuild target 的规范模式:DependsOnTargets 与 BeforeTargets、AfterTargets 的区别,Build-to-CoreBuild 三级模式,以及 XxxDependsOn 链式扩展模式。用于诊断或修复自定义 target 的反模式:Directory.Build.targets 重新定义 SDK target、target 替换而非扩展 CompileDependsOn、Outputs 与 Returns 误用导致返回过期结果、缺少 Inputs/Outputs 导致不必要的重新构建,或缺少 FileWrites 注册。不适用于增量构建调优或一般反模式审查(使用 msbuild 技能),也不适用于非 MSBuild 构建系统。
.NET测试命令执行
run-tests
选择并运行与仓库兼容的 .NET 测试命令:针对 MSTest、xUnit、NUnit 和 TUnit 的 classic、VSTest、bridged MTP 或 native MTP 语法。在运行 .NET 测试或需要给出测试命令/标志时使用:运行全部测试、单个测试、测试类、类别、trait 或目标框架、组合筛选器、--filter-query、--no-build、--diag、TRX、覆盖率收集、崩溃或挂起转储、筛选错误或无法识别的选项。不适用于仅做平台识别(使用 platform-detection)、编写或调试测试代码、解读覆盖率报告(使用 coverage-analysis)、CI 调查、迁移或持续的热重载循环。
.NET 性能剖析
profiling
使用免费的官方 .NET 诊断 CLI 工具在代码仓库中进行性能剖析和运行时调查:CPU、GC 压力、分配增长、异常风暴、锁竞争和慢代码。当 .NET 应用程序需要性能或运行时剖析时使用。不适用于用临时跟踪替代真实的性能或负载测试、无暂停风险计划的生产堆内存采集、崩溃转储(使用 dump-collect),或基准测试设计(使用 microbenchmarking)。
.NET 测试平台识别
platform-detection
识别 .NET 项目的测试平台、框架、命令模式,以及 SDK 样式与经典项目系统,并解析 global.json、项目文件、packages.config、Directory.Build.props 和 Directory.Packages.props 对 MSTest、xUnit、NUnit 和 TUnit 的优先级。当询问“使用哪种测试平台或框架”“VSTest 还是 MTP”或“该项目使用什么测试运行器”时使用,包括桥接设置、UseVSTest 退出选项,以及 VSTest/MTP 配置冲突。不适用于运行或筛选测试、命令、标志、TRX、转储或测试命令错误(使用 run-tests),也不适用于热重载或迁移请求。
Orleans 分布式系统设计
orleans
从每种原语的用途和失效模型出发设计 Microsoft Orleans 系统:grain、数字孪生、状态与数据库、事务、消息传递、流(streams)、计时器(timers)、提醒(reminders)、Durable Jobs(持久作业)、无状态工作进程、grain 服务、启动与托管。当任务需要做出 Orleans 设计决策时使用:检查版本与拓扑、选择原语、实现并验证。不适用于其他 actor 技术栈、批处理、纯关系型 CRUD,或不涉及 Orleans 决策的建议。