Determinar todos los tipos utilizados por un determinado tipo en C# mediante la reflexión

si tengo

class A
   public void DoStuff()
      B b;

struct B {}
struct C {}

y yo tengo typeof(A),

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

Is there a nice way to do this with reflection?

preguntado el 31 de julio de 12 a las 12:07

It's pretty easy to get all types of the miembros of A vía Type.GetFields, Type.GetProperties (o Type.GetMembers) and so on. But figuring out what types are used locally dentro de a method? Not so sure. -

Do you need this at runtime? Do you have access to the code, or do you just have the Type? -

1 Respuestas

Necesitas mirar el Método Cuerpo 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!");

Respondido 31 Jul 12, 12:07

Sorry if it was not clear from the post. I don't want to have to know the fact that B and C exist. if A also uses D, I'd like to find that out as well. - Lucas Meijer

As you can see in my code, mb.LocalVariables returns a list of all the types the method uses. That should be exactly what you need to discover if it uses B, C, D or even Z. - RB.

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.