获取特定 class 中使用的类型

Get types used inside a specific class

这是 class,我想获取其中使用的所有类型的列表:

public class TestClass : MonoBehaviour{
    private UIManager _manager;

    private void Initialize(UIManager manager){
        _manager = manager;
    }
}

然后我认为 运行 是这样的:

    Assembly assembly = typeof (TestClass).Assembly;
    foreach (Type type in assembly.GetTypes()){
        Debug.Log(type.FullName);
    }

只会给我 UIManager 类型。但它似乎给了我项目中使用的所有类型的列表。

我怎样才能得到这个 class 上使用的类型?

(如您所见,TestClass 继承自 MonoBehaviour,但我不想要那里使用的类型,我想要 TestClass 中专门使用的类型)。

如果您想知道用于 methods/fileds/properties 的类型 - 使用基本反射来枚举声明中使用的每个 methods/fields 和抓取类型。

即对于你会调用 Type.GetMethods and than dig through MethodInfo properties like MethodInfo.ReturnType 的方法来获取使用过的类型。可能递归地向下遍历每个基 class/interface 以找到所有依赖项。

如果您想知道方法内部使用了哪些类型,您需要使用某种 IL 解析器,因为反射不提供查看方法主体的方法。示例可在 Get types used inside a C# method body.

中找到

请注意,现有工具已经提供了类似的功能 - 即 ReSahrper 具有 "find code depending on module" 和 "find usages for types/methods/..."。

return符合预期。 Type.Assembly returns 声明类型的程序集(.dll、.exe)。在您的情况下,程序集是您项目的输出。因此 GetTypes 将 return 该程序集中包含的所有类型。

你想做的事情可以通过枚举你的Type中声明的方法和属性来实现。这是通过调用 Type.GetMethodsType.GetProperties 方法完成的。

像这样:

foreach(PropertyInfo prop in typeof(TestClass).GetProperties)
{
    //Access types.
}

foreach(MethodInfo method in typeof(TestClass).GetProperties)
{
    //Access types.
}

您需要 System.Assembly.GetReferencedAssemblies(),因此:

using System.Reflection;
...
Assembly       assembly     = Assembly.LoadFile(@"c:\path\to\some\arbitrary-assembly.dll");
AssemblyName[] dependencies = assembly.GetReferencedAssemblies();

留给 reader 的练习是构造递归树遍历以枚举完整的直接和间接程序集集。有人可能会注意到,这将需要加载 每个 引用的程序集。考虑在独立进程中进行此类检查或将程序集加载到 reflection-only context.