使用NRefactory从C#代码获取所有方法 [英] Get all methods from C# code using NRefactory

查看:536
本文介绍了使用NRefactory从C#代码获取所有方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用NRefactory API检索C#程序中的所有方法?

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

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

这会创建一个SyntaxTree,但是如何仅从SyntaxTree中获取方法列表?

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

推荐答案

深入探讨要从SyntaxTree中获取信息,您可以访问节点或使用类型系统.

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

要使用TypeSystem,您可以执行以下操作:

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

这篇关于使用NRefactory从C#代码获取所有方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆