在没有进行编译生成DLL的情况下,可以使用Roslyn对.cs文件进行解析,而获取类 函数 的有关信息
string sourceCode = @"public class MyClass
{
public int MyMethod(string param1, int param2)
{
// 方法实现
return 0;
}
}";
SyntaxTree tree = CSharpSyntaxTree.ParseText(sourceCode);
// 如果需要判断是否解析成功
var diagnostics = tree.GetDiagnostics();
if (diagnostics.Any(d => d.Severity == DiagnosticSeverity.Error))
{
Console.WriteLine("Syntax errors found:");
foreach (var diagnostic in diagnostics)
{
Console.WriteLine($"{diagnostic.Id}: {diagnostic.GetMessage()}");
}
}
else
{
// 遍历所有的成员声明
foreach (var memberDecl in tree.GetRoot().DescendantNodes().OfType<MemberDeclarationSyntax>())
{
string className = string.Empty;
if (memberDecl is ClassDeclarationSyntax classDeclaration)
{
// 获取类名
className = classDeclaration.Identifier.Text;
Console.WriteLine("类名:" + className);
}
// 检查是否为方法声明
if (memberDecl is MethodDeclarationSyntax methodDeclaration)
{
string methodName = methodDeclaration.Identifier.Text;
Console.WriteLine(" Function name:" + methodName);
string returnType = methodDeclaration.ReturnType.ToString();
Console.WriteLine($"Return type: {returnType}");
// 获取参数
foreach (var parameter in methodDeclaration.ParameterList.Parameters)
{
string paramName = parameter.Identifier.Text;
string paramType = parameter.Type!.ToString();
Console.WriteLine($"Parameter name: {paramName}, Type: {paramType}");
}
}
}
}
当然需要使用以下依赖
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis;