为了找出使用方法的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参数,也不处理通用参数。我相信那也忘记了其他细节。它只是表明可以做到。