简体   繁体   中英

Determining all types used by a certain 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 would be typeof(B) and not typeof(C) .

Is there a nice way to do this with reflection?

You need to look at the MethodBody class (there's a very good example of it's use in the link). This will let you write code like:

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!");
}

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