Determining all types used by a certain type in c# using reflection

耗尽温柔 提交于 2019-12-05 00:11:32

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/11739096/determining-all-types-used-by-a-certain-type-in-c-sharp-using-reflection

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!