如何在调用NormalizeWhitespace方法时阻止Lambda块语句中的新行

时间:2014-12-15 19:10:21

标签: c# roslyn

我有以下代码..

var tree  = CSharpSyntaxTree.ParseText(
 @"
     Func<string, string> parser = value =>
     {
         return string.Format(""Hello {0}"", value);
     };
");

var root = (CompilationUnitSyntax)tree.GetRoot();
var result = root.NormalizeWhitespace().GetText().ToString();

enter image description here

在打印输出时,NormalizeWhitespace方法将分号推送到新行。反正我们可以阻止这个吗?。

此外,是否可以将分号移近花括号。

感谢您的帮助。

1 个答案:

答案 0 :(得分:3)

因为字符串文字总是捕获换行符。因此,尝试在结束时结束字符串文字,而不是添加换行符以使括号看起来更好。

var tree  = CSharpSyntaxTree.ParseText(
// The trailing newline might help keep indentation on the first line correct
@"
     Func<string, string> parser = value =>
     {
         return string.Format(""Hello {0}"", value);
     };" // Not this string ends here
);

var root = (CompilationUnitSyntax)tree.GetRoot();
var result = root.NormalizeWhitespace().GetText().ToString();

不太优雅的方法包括在结果常量上调用string方法,如下所示:

var tree  = CSharpSyntaxTree.ParseText(
(@"
     Func<string, string> parser = value =>
     {
         return string.Format(""Hello {0}"", value);
     };
").Trim());    // This could also be .Trim('\n') to only remove the newlines before and after the text

var root = (CompilationUnitSyntax)tree.GetRoot();
var result = root.NormalizeWhitespace().GetText().ToString();