尧图网站设计 尧图网站设计YAOTU DESIGN
ARTICLE DETAIL

资讯详情

深耕网站设计与一线实操的经验洞察。

.NET编码规范05-Roslyn分析器与StyleCop

.NET编码规范05-Roslyn分析器与StyleCop .NET编码规范第 5 篇Roslyn 分析器与 StyleCop—— 代码质量与风格双保险前言如果.editorconfig是交通规则标识那么 Roslyn 分析器就是 24 小时执勤的交警 —— 它在代码编写的瞬间就开始工作实时检查你的代码是否合规。本文重点讲解 .NET 内置的 Roslyn 分析器体系CAxxxx / IDExxxx、第三方 StyleCop.Analyzers 的配置、以及两者的协同使用。一、Roslyn 分析器是什么Roslyn 是 .NET 的编译器平台它不只是把 C# 编译成 IL还对外开放了语法分析 API。分析器Analyzer就是基于 Roslyn API 的插件在编译时对代码进行静态分析。你的代码 → Roslyn 解析 → 语法树 → 分析器检查 → 诊断报告 ↓ 实时反馈到 IDE二、内置分析器CAxxxx 与 IDExxxx2.1 两大类规则前缀类别关注点示例CAxxxx代码质量分析潜在 Bug、性能、安全性CA2007缺少 ConfigureAwaitIDExxxx代码风格分析命名、格式、可读性IDE0004可以移除不必要的类型转换在visual studio中机场能看到CA和IDE的消息提醒2.2 常用 CA 规则// CA1001: 拥有可释放字段的类型应实现 IDisposablepublicclassResourceHolder// ⚠️ 未实现 IDisposable{privateFileStream_fileStream;// IDisposable 字段}// CA1062: 验证公共方法的参数publicvoidValidateUser(Useruser)// ⚠️ 未验证 null{varnameuser.Name.ToUpper();}// 正确publicvoidValidateUser(Useruser){ArgumentNullException.ThrowIfNull(user);varnameuser.Name.ToUpper();}// CA1303: 不要将文本作为参数传递Console.WriteLine(Welcome back, user.Name);// ⚠️ 应本地化// 或使用资源文件// CA1822: 不访问实例数据的成员可以标记为 staticpublicstringFormatName(stringname)// ⚠️ 可以设为 static{returnname.Trim();}// CA2007: 等待的任务不需要 ConfigureAwaitvarresultawait_httpClient.GetAsync(url).ConfigureAwait(false);// ⚠️ .NET Core 不需要此调用2.3 常用 IDE 规则// IDE0004: 移除不必要的类型转换intx(int)5;// ⚠️ 不必要的强制转换// IDE0017: 使用对象初始化器varusernewUser();// ⚠️ 可以用对象初始化器user.NameJohn;user.Age30;// 应该改为varusernewUser{NameJohn,Age30};// IDE0031: 使用 null 传播if(user!nulluser.Address!null)// ⚠️ 可以用 ?.{Console.WriteLine(user.Address.City);}// 应该改为Console.WriteLine(user?.Address?.City);// IDE0063: 简化 using 语句using(varfilenewFileStream(...))// ⚠️ 可以简化{// ...}// 应该改为 (C# 8):usingvarfilenewFileStream(...);// IDE0090: 简化 new 表达式CustomercustomernewCustomer();// ⚠️ 可以用 new()// 应该改为Customercustomernew();三、配置分析器严重性在.editorconfig中配置每条规则的严重级别[*.cs] # 将重要规则设为 error编译失败 dotnet_diagnostic.CA1001.severity error # 必须实现 IDisposable dotnet_diagnostic.CA1062.severity error # 必须验证参数 dotnet_diagnostic.CA2007.severity warning # ConfigureAwait 检查 # 将风格规则设为 suggestion/warning dotnet_diagnostic.IDE0017.severity warning # 对象初始化器 dotnet_diagnostic.IDE0031.severity suggestion # null 传播全局禁用特定规则# 禁用某条不合适的规则 dotnet_diagnostic.CA1707.severity none # 禁用标识符不应包含下划线四、StyleCop.Analyzers更严格的风格审查4.1 安装PackageReferenceIncludeStyleCop.AnalyzersVersion1.2.0-beta.556PrivateAssetsall/PrivateAssetsIncludeAssetsruntime; build; native; contentfiles; analyzers/IncludeAssets/PackageReference注意当前稳定版是 1.2.0-beta.556已经相当成熟。生产项目可以考虑使用此版本。4.2 StyleCop 规则分类及核心规则规则前缀类别典型规则SA1xxx布局SA1503: 大括号不能省略SA1xxx间距SA1000: 关键字后必须有空格SA1xxx可读性SA1116: 用括号分隔多条件SA12xx排序SA1200: using 必须放在命名空间外SA14xx可维护性SA1401: 字段必须是私有4.3 核心规则示例// SA1503: 大括号不能省略if(isValid)DoSomething();// ⚠️ StyleCop 强制要求大括号// ✅ 正确if(isValid){DoSomething();}// SA1200: using 指令必须放在命名空间外部namespaceMyApp{usingSystem;// ⚠️ StyleCop 要求放在外面}// ✅ 正确usingSystem;namespaceMyApp{}// SA1611: 方法参数必须有文档注释publicvoidUpdateUser(stringuserId)// ⚠️ userId 缺少 param{}// ✅ 正确/// summary更新用户信息。/summary/// param nameuserId用户ID。/parampublicvoidUpdateUser(stringuserId){}4.4 使用stylecop.json微调在项目根目录创建stylecop.json{$schema:https://raw.githubusercontent.com/DotNetAnalyzers/StyleCopAnalyzers/master/StyleCop.Analyzers/StyleCop.Analyzers/Settings/stylecop.schema.json,settings:{orderingRules:{usingDirectivesPlacement:outsideNamespace,systemUsingDirectivesFirst:true},documentationRules:{companyName:YourCompany,copyrightText:Copyright (c) {companyName}. All rights reserved.,xmlHeader:false,fileNamingConvention:stylecop},namingRules:{allowCommonHungarianPrefixes:false,allowedHungarianPrefixes:[]},layoutRules:{newlineAtEndOfFile:require}}}在.csproj中引用ItemGroupAdditionalFilesIncludestylecop.json//ItemGroup五、内置分析器 vs StyleCop —— 如何选择维度内置 Roslyn 分析器StyleCop.Analyzers安装.NET SDK 自带无需安装需 NuGet 引用代码质量强Bug、性能、安全弱主要聚焦风格代码风格中等强极其严格强制文档注释命名规则通过 .editorconfig自带 stylecop.jsonXAML 分析支持不支持配置复杂度中较高需要 stylecop.json推荐场景所有项目的基础分析对文档和格式有极高要求的项目推荐组合方案 A推荐内置分析器 .editorconfig 命名规则 方案 B严格要求内置分析器 StyleCop.Analyzers stylecop.json 方案 C极客路线内置分析器 StyleCop 自定义分析器对于大多数团队方案 A 足以覆盖 90% 的需求。六、自定义分析器简介如果内置规则不够满足特殊需求可以编写自定义分析器// 示例检测 Controller 方法是否缺少 [Authorize][DiagnosticAnalyzer(LanguageNames.CSharp)]publicclassControllerAuthorizationAnalyzer:DiagnosticAnalyzer{publicconststringDiagnosticIdCUSTOM001;privatestaticreadonlyDiagnosticDescriptorRulenew(DiagnosticId,Controller actions must be authorized,The action method {0} is not protected by authorization,Security,DiagnosticSeverity.Error,isEnabledByDefault:true);// ... 分析方法语法树}自定义分析器开发已超出本文范围建议从 Microsoft 官方教程 入门。七、实战分析器落地三步走第一步在Directory.Build.props中全局启用ProjectPropertyGroupAnalysisLevellatest-recommended/AnalysisLevelEnforceCodeStyleInBuildtrue/EnforceCodeStyleInBuildTreatWarningsAsErrorsfalse/TreatWarningsAsErrors/PropertyGroup/Project第二步在.editorconfig中细化规则[*.cs] # 核心质量规则 → error dotnet_diagnostic.CA1001.severity error dotnet_diagnostic.CA1062.severity error # 风格建议 → suggestion先提示后收紧 dotnet_diagnostic.IDE0017.severity suggestion dotnet_diagnostic.IDE0031.severity suggestion第三步CI/CD 中强制检查# GitHub Actions 示例-name:Build with analysisrun:dotnet build--configuration Release /p:TreatWarningsAsErrorstrue
返回列表