简体   繁体   中英

Get documentation comment from ArgumentSyntax node

How I can read one line documentation comment from ArgumentSyntax ?

This is situation for Roslyn analyzer:

SomeInstance.SomeMethod(SomeStaticClass.SomeStruct.CommentedField);

The class in the argument looks like this:

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

I have ArgumentSyntax with result "SomeStaticClass.SomeStruct.CommentedField" , but there is not access to document. I tried SemanticModel but from it I only have type Int64 .

You should be able to use the Expression property of the ArgumentSyntax to obtain an expression which would then allow you to obtain the SymbolInfo for the accessed property like this:

    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();

In case you wish to retrieve another type of comment, you could exchange the analysis of the leading trivia to for instance get non-documentation comments or multiline documentation comments.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM