简体   繁体   中英

Is there a way to find which methods were called within a method via reflection?

I am building a v4.5 C#/.NET application and have to find which methods are dependent on a method. I want to list those methods out.

For example, if I have a method in a class and if this method uses another method:

public void Test()
{
    CallMethodA();
    CallMethodB();
}

When I pass in method Test to my application, I want it to print out CallMethodA and CallMethodB via reflection.

So far I have created this:

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)
    {

    }
}

Mono.Cecil would be a good place to start. This question has lots of tutorials linked in answers.

However, this will only give you static analysis, ie the method calls at compile time. If you have method calls to an interface or virtual method then you won't know what other methods are actually being called at run-time. If you want to know what code was actually called at run-time you need to collect coverage information via instrumentation.

It is very much like creating your own application like .NET Reflector or dotPeek . If you want to know what calls are made within method of a class, you have to create something like Reflector. Also, do check out ILSpy ; it can be of help.

About ILSpy

ILSpy is the open-source .NET assembly browser and decompiler.

Development started after Red Gate announced that the free version of .NET Reflector would cease to exist by end of February 2011.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM