Is their a way in Roslyn to go through a Method in C# line by line?
What I try to do is analyze comments inside a UnitTest do build a Documentation:
This is a Example Test which I want to analyze
[TestClass]
public class ClassToAnalyze
{
[TestMethod]
public void MethodToAnalyze()
{
// * Start Testing
Assert.IsTrue(true);
// * Test something other
var text = new string("foobar");
Assert.IsNotNull(text);
// ** Test additional strings
Assert.AreEqual("foobar",text);
// + Test Numbers
TestNumbers();
}
private void TestNumbers()
{
// ** Test integer
var count = 3;
Assert.AreEqual(3, count);
// ** Test Double
var pi = 3.14;
Assert.IsTrue(pi > 0);
}
}
You can see the comments which are marked which an asterix, this is doc level 1 an the one with 2 asterix are Level 2. Like an unsorted list in markdown.
But the comment with the + sign marks that after this their is a method-call where are also comments include for the documentation.
For Example: I analyze the code of the Testmethod, this works totaly fine. But the Comment // + Test Numbers indicates that their are additional comments in the methods TestNumbers() . I already build a way to analyze the Comments in TestNumbers() but I do not get a connection during analyze between the comment // + Test Numbers and the call TestNumbers() in the line after.
What I tried:
I tried this but I only managed to get a list of statements and I did not find a way to get the Trivia before every statement.
How could I do this?
foreach (var method in _classDeclarationSyntax.DescendantNodes().OfType<MethodDeclarationSyntax>())
{
var blockSyntax = methodDeclarationSyntax.Body;
var syntaxNodes = blockSyntax.ChildNodes();
}
So after a lot of try and error it is pretty easy. The thing to use is CSharpSyntaxWalker and give him a BlockSyntax.
public class MethodBodySyntaxWalker : CSharpSyntaxWalker
{
public override void VisitLocalDeclarationStatement(LocalDeclarationStatementSyntax node)
{
if (node.HasLeadingTrivia)
{
Trace.WriteLine(node.GetLeadingTrivia().ToFullString().Trim());
}
Trace.WriteLine(node.ToString());
}
public override void VisitExpressionStatement(ExpressionStatementSyntax node)
{
if (node.HasLeadingTrivia)
{
Trace.WriteLine(node.GetLeadingTrivia().ToFullString().Trim());
}
Trace.WriteLine(node.ToString());
}
}
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.