Roslyn解析.cs文件

在没有进行编译生成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;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值