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