面试题答案
一键面试实现思路
- 使用
Microsoft.CodeAnalysis.CSharp.CSharpSyntaxTree
将C#代码字符串解析为语法树。 - 通过语法树获取根节点,然后遍历语法树节点。
- 在遍历过程中,筛选出类型为
MethodDeclarationSyntax
的节点,这些节点即为方法声明。
关键代码示例
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static List<MethodDeclarationSyntax> GetMethodDeclarations(string sourceCode)
{
var syntaxTree = CSharpSyntaxTree.ParseText(sourceCode);
var root = syntaxTree.GetRoot();
return root.DescendantNodes()
.OfType<MethodDeclarationSyntax>()
.ToList();
}
}
你可以这样调用上述方法:
class Test
{
static void Main()
{
string sourceCode = @"
class MyClass
{
public void MyMethod1() { }
private int MyMethod2(int a) { return a; }
}
";
var methods = GetMethodDeclarations(sourceCode);
foreach (var method in methods)
{
Console.WriteLine(method.Identifier.Text);
}
}
}