C# 反射和查找所有引用 [英] C# reflection and finding all references
问题描述
给定一个 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 Reflector 之类的工具来执行此操作,但反思是好的,可能是必要的.
I don't want to use a tool like .NET Reflector to do this, but reflection is fine and probably necessary.
推荐答案
要找出方法 MyClass.Foo()
在哪里使用,您必须分析所有具有对包含 MyClass
的程序集的引用.我写了一个简单的概念证明,说明这段代码的样子.在我的示例中,我使用了这个库(它是只是 单个 .cs 文件)由 Jb Evain 编写:
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);
}
}
我写了这段代码来打印出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())
);
}
}
它给了我以下输出:
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屋!