确定通过使用反射在C#中某一类型中使用的所有类型 [英] Determining all types used by a certain type in c# using reflection

查看:134
本文介绍了确定通过使用反射在C#中某一类型中使用的所有类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有

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

struct B {}
struct C {}

和我有 typeof运算(A)

我想获得在这种情况下,将使用A中的所有类型的列表 typeof运算(B),而不是 typeof运算(C)

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?

推荐答案

您需要看 MethodBody 类(有它的一个很好的例子就是在链接使用)。这将让你写类似的代码:

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

这篇关于确定通过使用反射在C#中某一类型中使用的所有类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆