Defining all types used by a particular type in C # using reflection

if i have

class A
{
   public void DoStuff()
   {
      B b;
   }
}

struct B {}
struct C {}

and I have typeof(A),

I would like to get a list of all types used by A. in this case it will be typeof(B), not typeof(C).

Is there a good way to do this with reflection?

+5
source share
1 answer

You need to look at the MethodBody class (there is a very good example of using it in a link). This will allow you to write code, for example:

MethodInfo mi = typeof(A).GetMethod("DoStuff");
MethodBody mb = mi.GetMethodBody();
foreach (LocalVariableInfo lvi in mb.LocalVariables)
{
    if (lvi.LocalType == typeof(B))
        Console.WriteLine("It uses a B!");
    if (lvi.LocalType == typeof(C))
        Console.WriteLine("It uses a C!");
}
+8
source

All Articles