从TextLine获得评论

时间:2019-03-21 08:58:17

标签: c# roslyn roslyn-code-analysis

我有

var sourceText = SourceText.From(filestream);
var firstLine = sourceText.Lines.FirstOrDefault();

这给了我第一行源代码为TextLine。我需要将注释解析为字符串,但我想为此使用Roslyn。如何使用Roslyn从TextLine提取单行注释?

1 个答案:

答案 0 :(得分:1)

您需要将文本解析为语法树,然后搜索所需类型的琐事。您有几种语法,包括SingleLineCommentTrivia, MultiLineCommentTrivia, ...

var tree = CSharpSyntaxTree.ParseText(sourceText, path: filename);
var root = tree.GetCompilationUnitRoot();

var comment = root.DescendantTrivia()
    .OfType<SyntaxTrivia>()
    .FirstOrDefault(s=> s.IsKind(SyntaxKind.SingleLineCommentTrivia)) // Here you decide what you want to filter on
    .ToFullString();

有关更多详细信息,请参见https://docs.microsoft.com/en-us/dotnet/api/microsoft.codeanalysis.csharp.syntaxkind?view=roslyn-dotnet