【发布时间】:2020-08-28 17:35:05
【问题描述】:
场景:我正在尝试使用 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);
}
}
}
我错过了什么?
【问题讨论】: