从 ArgumentSyntax 节点获取文档注释

时间:2021-05-14 06:44:54

标签: c# comments documentation roslyn

如何从 ArgumentSyntax 中读取一行文档注释?

这是 Roslyn 分析器的情况:

SomeInstance.SomeMethod(SomeStaticClass.SomeStruct.CommentedField);

参数中的类如下所示:

public static class SomeStaticClass 
{
      public struct SomeStruct 
      {
             /// <summary>Desired documentation comment</summary>
             public const Int64 CommentedField = 123;
      }
}

我有 ArgumentSyntax,结果为 "SomeStaticClass.SomeStruct.CommentedField",但无法访问文档。我试过 SemanticModel 但从中我只有类型 Int64

1 个答案:

答案 0 :(得分:1)

您应该能够使用 ArgumentSyntax 的 Expression 属性来获取一个表达式,然后您就可以像这样获取所访问属性的 SymbolInfo:

    var expression = argument.Expression as MemberAccessExpressionSyntax;
    var symbolInfo = semanticModel.GetSymbolInfo(expression.Name);

    // Get the documentation comment XML in XML form.
    var documentationCommentXml = symbolInfo.Symbol.GetDocumentationCommentXml();

    // Alternatively, you can use the syntax to find the FieldDeclarationSyntax, 
    // if it is within the solution and extract the trivia
    var fieldDeclarationSyntax = declaringSyntax
                    .AncestorsAndSelf().OfType<FieldDeclarationSyntax>().Single();
    var leadingTrivia = fieldDeclarationSyntax.GetLeadingTrivia();
    var documentationTrivia = leadingTrivia.FirstOrDefault(
                    trivia => trivia.IsKind(SyntaxKind.SingleLineDocumentationCommentTrivia));
    // Retrieves the comment itself in comment-form
    var commentFromTrivia = documentationTrivia.ToFullString();

如果您希望检索其他类型的评论,您可以交换对主要琐事的分析,例如获取非文档评论或多行文档评论。

相关问题