Get all methods from C# code using NRefactory

2019-07-22 04:28发布

How do I retrieve all the methods in a C# program using the NRefactory API ?

CSharpParser parser = new CSharpParser();
SyntaxTree tree = parser.Parse(code);

This creates a SyntaxTree but how do I get ONLY the list of methods from this SyntaxTree?

1条回答
放荡不羁爱自由
2楼-- · 2019-07-22 04:52

There is an in depth article about using NRefactory available on CodeProject.

To get information from the SyntaxTree you can either visit the nodes or use the type system.

To visit the method declaration nodes you can do:

    var parser = new CSharpParser();
    SyntaxTree tree = parser.Parse(code);

    tree.AcceptVisitor(new MyVistor());

class MyVistor : DepthFirstAstVisitor
{
    public override void VisitMethodDeclaration(MethodDeclaration methodDeclaration)
    {
        Console.WriteLine(methodDeclaration.Name);
        base.VisitMethodDeclaration(methodDeclaration);
    }
}

To use the TypeSystem you can do:

    var parser = new CSharpParser();
    SyntaxTree tree = parser.Parse(code, "test.cs");

    CSharpUnresolvedFile file = tree.ToTypeSystem();
    foreach (IUnresolvedTypeDefinition type in file.TopLevelTypeDefinitions) {
        foreach (IUnresolvedMethod method in type.Methods) {
            Console.WriteLine(method.Name);
        }
    }
查看更多
登录 后发表回答