C#反思和查找所有引用 [英] C# reflection and finding all references

查看:183
本文介绍了C#反思和查找所有引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定一个DLL文件,我希望能够找到所有的DLL文件中的一个方法调用。我怎样才能做到这一点?

Given a DLL file, I'd like to be able to find all the calls to a method within that DLL file. How can I do this?

从本质上讲,我该怎么办编程什么的Visual Studio已经呢?

Essentially, how can I do programmatically what Visual Studio already does?

我不想使用像 .net反射一个工具来做到这一点,但反映是很好,大概必要的。

I don't want to use a tool like .NET Reflector to do this, but reflection is fine and probably necessary.

推荐答案

要找出一个方法 MyClass.Foo()时,你要分析所有类那必须包含 MyClass的的程序集的引用的所有组件。我写这code怎么可以像概念的一个简单证明。在我的例子我用这个库(这只是的a按JB Evain写入单个.cs文件):

To find out where a method MyClass.Foo() is used, you have to analyse all classes of all assemblies that have a reference to the assembly that contains MyClass. I wrote a simple proof of concept of how this code can look like. In my example I used this library (it's just a single .cs file) written by Jb Evain:

我写了一个小测试类来分析:

I wrote a little test class to analyse:

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

和我写这篇code打印出在使用的所有方法TestClass.Test()

And I wrote this code to print out all the methods used within 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())
        );
    }
}

它给了我下面的输出:

It gave me the following output:

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

这个例子是没有完成显然不能,因为它不处理ref和out参数,它不处理的通用参数。我相信,忘记了其他细节为好。它只是表明,它可以做到的。

This example is obviously far from complete, because it doesn't handle ref and out parameters, and it doesn't handle generic arguments. I am sure that forgot about other details as well. It just shows that it can be done.

这篇关于C#反思和查找所有引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆