如何通过.editorconfig限制表达式体方法的三元运算符嵌套深度
问题:如何通过.editorconfig限制表达式体方法中三元运算符的最大嵌套深度?
我编写了如下C#方法:
public IModelBinder GetBinder(ModelBinderProviderContext context) { if (context == null) { throw new ArgumentNullException(nameof(context)); } if (context.Metadata.ModelType == typeof(BaseGetAllRequest) || context.Metadata.ModelType.IsSubclassOf(typeof(BaseGetAllRequest))) { return new BinderTypeModelBinder(typeof(SearchFiltersBinder)); } return null; }
运行Visual Studio Code的代码清理后,该方法被转换为包含多层三元运算符的表达式体方法,可读性有所下降:
public IModelBinder GetBinder(ModelBinderProviderContext context) => context == null ? throw new ArgumentNullException(nameof(context)) : context.Metadata.ModelType == typeof(BaseGetAllRequest) || context.Metadata.ModelType.IsSubclassOf(typeof(BaseGetAllRequest)) ? new BinderTypeModelBinder(typeof(SearchFiltersBinder)) : (IModelBinder)null;
我已启用表达式体方法特性,但希望限制表达式体方法中三元运算符的最大嵌套深度(最多使用1个问号),请问能否通过.editorconfig实现?
回答
目前.editorconfig没有直接控制表达式体方法中三元运算符嵌套深度的专属配置项,但可以通过调整代码风格规则,避免格式化工具生成多层嵌套的三元表达式:
1. 限制三元表达式的转换场景
修改dotnet_style_prefer_conditional_expression_over_return配置,仅允许在单行时将if-else转换为三元表达式,这样多层判断的逻辑因无法写成单行,就不会被转成嵌套三元:
dotnet_style_prefer_conditional_expression_over_return = when_on_single_line:suggestion
2. 缩小表达式体方法的适用范围
如果希望仅在简单场景下使用表达式体方法,可以调整dotnet_style_prefer_expression_bodied_methods的取值,比如只允许属性访问器使用表达式体,或者仅当方法体能写成单行时才启用:
# 仅允许属性、索引器等访问器使用表达式体 dotnet_style_prefer_expression_bodied_methods = accessors_only:suggestion # 或者仅当方法体可写成单行时才启用表达式体 dotnet_style_prefer_expression_bodied_methods = when_on_single_line:suggestion
3. 严格禁用嵌套三元(可选)
如果需要强制禁止嵌套三元表达式,可以引入第三方分析器(如StyleCop.Analyzers),启用其SA1118规则(禁止嵌套三元表达式),并在.editorconfig中配置规则的严重级别,确保代码不符合要求时触发提示或错误。
内容的提问来源于stack exchange,提问作者Jakob Busk Sørensen
相关产品推荐
相关产品推荐

