如何通过EditorConfig在VS中正确格式化C# statement lambdas?
解决C#语句Lambda的EditorConfig格式化问题
我使用Visual Studio开发C#程序,通过EditorConfig指定代码格式化规则,其余配置均正常生效,但语句lambda的格式化始终不符合预期。
代码示例
原始代码:
public static void Main( string[] args ) { Console.CancelKeyPress += ( _, _ ) => { Console.WriteLine( "Hello!" ); }; }
VS格式化后的实际结果:
public static void Main( string[] args ) { Console.CancelKeyPress += ( _, _ ) => { Console.WriteLine( "Hello!" ); }; }
预期格式化效果:
public static void Main( string[] args ) { Console.CancelKeyPress += ( _, _ ) => { Console.WriteLine( "Hello!" ); }; }
解决方案
在.editorconfig文件的[*.cs]配置区块中添加以下配置项:
# 开启语句lambda体的缩进 csharp_indent_lambda_body = true
如果上述配置未生效,可以补充设置标签缩进规则:
# 调整lambda块的缩进层级 csharp_indent_labels = one_less_than_current
配置说明
csharp_indent_lambda_body = true:专门控制语句lambda的缩进逻辑,开启后lambda的大括号会相对于箭头缩进一个层级,大括号内的代码再正常缩进,完全匹配预期效果。csharp_indent_labels = one_less_than_current:该配置控制标签类语法(包括lambda箭头后的代码块)的缩进方式,设置为one_less_than_current会让lambda块的大括号相对于当前上下文缩进一级,确保整体结构对齐。
添加配置后,重新调用Visual Studio的格式化功能,即可得到符合预期的代码格式。
内容的提问来源于stack exchange,提问作者Mike Nakis
相关产品推荐
相关产品推荐

