如何通过.editorconfig修复C#模式匹配代码的格式问题
如何通过.editorconfig保留模式匹配语句的自定义格式?
我有以下代码:
internal class Program { private static bool IsMatchingThing1(IThing thing) { return thing is AThing { Children: [ BThing ] }; } private static bool IsMatchingThing2(IThing thing) { return thing is AThing { Children: [ BThing ] }; } } internal interface IThing; internal class AThing : IThing { public List<IThing> Children { get; set; } = new(); } internal class BThing : IThing { public List<IThing> Children { get; set; } = new(); }
方法IsMatchingThing1和IsMatchingThing2的模式匹配语句格式略有不同,但都符合我的要求。不过触发自动格式化(比如重新输入末尾分号)时,Visual Studio会将其重新格式化为:
private static bool IsMatchingThing1(IThing thing) { return thing is AThing { Children: [ BThing ] }; } private static bool IsMatchingThing2(IThing thing) { return thing is AThing { Children: [ BThing ] }; }
我希望保留自己的两种格式之一(不介意固定为其中一种),且需要处理层级更深的模式,不能全部放在一行。请问在.editorconfig中可以设置哪些选项,既能让这些语句保持合理格式,又不会让dotnet format修改这些方法的代码,同时保留其他部分的原有格式?
dotnet.exe版本:9.0.300
关键.editorconfig配置选项
你可以通过以下配置调整模式匹配的格式化行为,选择符合你偏好的组合:
1. 对齐模式匹配块的大括号
要让AThing后的大括号与类型本身对齐(对应IsMatchingThing2的格式),添加:
csharp_align_pattern_matching_block = true
该设置会避免模式块大括号被额外缩进,保持和类型一致的层级。
2. 控制集合初始化器的换行与缩进
- 若偏好
IsMatchingThing1中Children:直接紧跟集合初始化器的格式:csharp_new_line_before_colon_in_collection_initializer = false - 若偏好
IsMatchingThing2中Children:后换行的格式:csharp_new_line_before_colon_in_collection_initializer = true
同时,确保集合内元素的缩进与属性保持一致:
csharp_indent_collection_initializer = true
这会让BThing的缩进层级和Children:相同,避免过度缩进。
3. 控制对象模式的大括号换行
如果希望AThing和大括号在同一行(IsMatchingThing1的格式),调整大括号换行规则:
csharp_new_line_before_open_brace = methods, properties, control_blocks, types, anonymous_types
注意移除object_collections,这样对象模式的大括号会紧跟类型,而不会自动换行。
4. 局部禁用格式化(可选)
如果上述配置仍无法完全匹配你的需求,可以在代码中添加注释,精准禁用特定代码块的格式化:
// dotnet_format disable private static bool IsMatchingThing1(IThing thing) { return thing is AThing { Children: [ BThing ] }; } // dotnet_format restore
这种方式不会影响其他代码的自动格式化行为。
完整配置示例(适配IsMatchingThing2格式)
[*.cs] # 对齐模式匹配块的大括号 csharp_align_pattern_matching_block = true # 集合初始化器冒号后换行 csharp_new_line_before_colon_in_collection_initializer = true # 集合元素与属性缩进一致 csharp_indent_collection_initializer = true # 保持其他代码的默认大括号换行规则 csharp_new_line_before_open_brace = methods, properties, control_blocks, types, anonymous_types, object_collections
内容的提问来源于stack exchange,提问作者fractor
相关产品推荐
相关产品推荐

