问题描述
场景:我正在尝试使用Roslyn将一组C#源代码片段合并为一个代码片段。
问题:使用前导注释解析不同的类时,不会保留第一类(示例中的SomeClass
)上方的注释。对于第二类(AnotherClass
),注释保留...
下面的代码演示了该问题。在控制台程序中使用此程序(并安装Microsoft.CodeAnalysis.CSharp nuget程序包)
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using System.Collections.Generic;
using System.Diagnostics;
using System;
namespace roslyn01
{
class Program
{
static void Main(string[] args)
{
var input = new[]
{
"// some comment\r\nclass SomeClass {}","// another comment\r\nclass AnotherClass {}",};
// parse all input and collect members
var members = new List<MemberDeclarationSyntax>();
foreach (var item in input)
{
var SyntaxTree = CSharpSyntaxTree.ParseText(item);
var compilationunit = (compilationunitSyntax)SyntaxTree.GetRoot();
members.AddRange(compilationunit.Members);
}
// assemble all members in a new compilation unit
var result = SyntaxFactory.compilationunit()
.AddMembers(members.ToArray())
.normalizeWhitespace()
.ToString();
var expected = @"// some comment
class SomeClass
{
}
// another comment
class AnotherClass
{
}";
Console.WriteLine(result);
// the assert fails; the first comment ('// some comment') is missing from the output
Debug.Assert(expected == result);
}
}
}
我想念什么?
解决方法
将ToString()
转换为ToFullString()
时,您使用的是CompilationUnitSyntax
而不是string
。 ToString()
返回删除前导和尾随琐事(包括注释)的字符串,但是ToFullString()
不会删除此琐事。您可以在代码文档中看到它:
//
// Description:
// Returns the string representation of this node,not including its leading and
// trailing trivia.
//
// Returns:
// The string representation of this node,not including its leading and trailing
// trivia.
//
// Comments:
// The length of the returned string is always the same as Span.Length
public override string ToString();
//
// Description:
// Returns full string representation of this node including its leading and trailing
// trivia.
//
// Returns:
// The full string representation of this node including its leading and trailing
// trivia.
//
// Comments:
// The length of the returned string is always the same as FullSpan.Length
public virtual string ToFullString();