您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

C#反射并找到所有引用

C#反射并找到所有引用

为了找出使用方法MyClass.Foo()位置,您必须分析所有对包含的程序集的引用的程序集的所有类MyClass。我写了一个简单的概念证明,以证明这段代码的样子。在我的示例中,我使用由Jb Evain编写的该库(只是一个.cs文件):

我写了一点测试课来分析:

public class TestClass
{
    public void test()
    {
        Console.WriteLine("Test");
        Console.Write(10);
        DateTime date = DateTime.Now;
        Console.WriteLine(date);
    }
}

我编写了这段代码,以打印出其中使用的所有方法TestClass.test()

MethodBase methodBase = typeof(TestClass).getmethod("Test");
var instructions = MethodBodyReader.GetInstructions(methodBase);

foreach (Instruction instruction in instructions)
{
    MethodInfo methodInfo = instruction.Operand as MethodInfo;

    if(methodInfo != null)
    {
        Type type = methodInfo.DeclaringType;
        ParameterInfo[] parameters = methodInfo.GetParameters();

        Console.WriteLine("{0}.{1}({2});",
            type.FullName,
            methodInfo.Name,
            String.Join(", ", parameters.Select(p => p.ParameterType.FullName + " " + p.Name).ToArray())
        );
    }
}

它给了我以下输出

System.Console.WriteLine(System.String value);
System.Console.Write(system.int32 value);
System.DateTime.get_Now();
System.Console.WriteLine(System.Object value);

这个示例显然还远远不够完整,因为它不处理ref和out参数,也不处理通用参数。我相信那也忘记了其他细节。它只是表明可以做到。

c# 2022/1/1 18:18:10 有488人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶