Get all methods from C# code using NRefactory

帅比萌擦擦* 提交于 2019-12-24 04:40:56

问题


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


来源:https://stackoverflow.com/questions/25468265/get-all-methods-from-c-sharp-code-using-nrefactory

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!