Get all methods from C# code using NRefactory

2019-07-22 04:33发布

问题:

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:

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