List closed types that runtime has created from open generic types

前端 未结 2 1567
时光取名叫无心
时光取名叫无心 2021-02-14 11:35

When I list all the types in the current AppDomain, I see my generic types with the generic placeholders. However, if I instantiate my generic types with a type and then list al

2条回答
  •  清歌不尽
    2021-02-14 12:26

    Ivan's answer is mostly right, but claiming that assembly metadata doesn't contain any information about constructed types is not quite correct. All constructed types are defined in assembly that uses them and tools like Mono.Cecil let you see it. Constructed types are not exposed through reflection and even Mono.Cecil makes it quite hard to locate them all.

    Basically you have to walk through all types that are used in the assembly, e.g. types of properties, return types, local variable types, etc. This information is contained in assembly metadata and reasonably easy to enumerate with Mono.Cecil. Then just apply simple filter that detects whether the type is constructed. Note that you might have to walk through several assemblies that reference the generic type definition in order to find all types constructed from it.

    There are two limitations to this solution. Firstly, types constructed via reflection naturally don't appear in any assembly. Secondly, some constructed types are embedded in generic types/methods and their generic type arguments are known only after their parent type/method is instantiated with particular generic type arguments.

提交回复
热议问题