给定一个 DLL 文件,我希望能够找到对该 DLL 文件中某个方法的所有调用。我怎样才能做到这一点?
本质上,我如何以编程方式完成 Visual Studio 已经完成的工作?
我不想使用像这样的工具.NET反射器要做到这一点,但反思是可以的,而且可能是必要的。
找出方法在哪里MyClass.Foo()
使用时,您必须分析引用包含以下内容的程序集的所有程序集的所有类MyClass
。我写了一个简单的概念证明来证明这段代码的样子。在我的例子中我使用了这个图书馆(只是单个 .cs 文件)由 Jb Evain 撰写:
我写了一个小测试类来分析:
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 参数,也不处理泛型参数。我确信他也忘记了其他细节。它只是表明它可以做到。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)