我希望能够在使用Roslyn解析C#源代码时阅读XML文档注释。
/// <summary>
/// Documentation...
/// </summary>
我尝试在ParseOptions中设置ParseDocumentationComments,但似乎没有效果?
var parseOptions = ParseOptions.Default.WithParseDocumentationComments(true);
SyntaxTree unit = SyntaxTree.ParseFile(file, parseOptions);
最佳答案
您需要:
LeadingTrivia
Compilation
,找到具有XML doc注释的Symbol
并在其上使用GetDocumentationComment()
方法。 一个完整的例子:
using Roslyn.Compilers.CSharp;
using System;
using System.Linq;
class Program
{
static void Main(string[] args)
{
var tree = SyntaxTree.ParseText(@"
/// <summary>This is an xml doc comment</summary>
class C
{
}");
var classNode = (ClassDeclarationSyntax)tree.GetRoot().Members.First();
var trivia = classNode.GetLeadingTrivia().Single(t => t.Kind == SyntaxKind.DocumentationCommentTrivia);
var xml = trivia.GetStructure();
Console.WriteLine(xml);
var compilation = Compilation.Create("test", syntaxTrees: new[] { tree });
var classSymbol = compilation.GlobalNamespace.GetTypeMembers("C").Single();
var docComment = classSymbol.GetDocumentationComment();
Console.WriteLine(docComment.SummaryTextOpt);
}
}