如何检索由.NET运行时产生的所有封闭式泛型类型的列表?封闭式、类型、列表、NET

2023-09-05 03:09:38 作者:努力变优秀

根据MSDN文档,.NET运行时将动态地根据上需要的基础泛型类型定义生成闭合类型。

According to MSDN documentation, the .NET runtime will dynamically generate closed types based on generic type definitions on an as-needed basis.

https://msdn.microsoft.com/en-us/library/ f4a6ta2h.aspx

是否有可能检索的System.Type 实例的集合对应于运行时生成的封闭类型?

Is it possible to retrieve a collection of System.Type instances corresponding to those runtime-generated closed types?

推荐答案

生成列表动态地使用静态构造函数。这不是线程安全的,但唯一的线程争发生在静态构造函数运行之后首次创建的每一个封闭式,因此这可能不是一个问题,具体取决于您的code构造。

Build the list dynamically using the static constructor. This is not thread safe but the only thread contention happens when the static constructor runs right after the each closed type is first created, so that might not be an issue depending on how your code is constructed.

即。如果所有这些泛型类型的初始接入发生在一个单独的线程,你还有什么可担心的。

i.e. if all of your initial access to these generic types happens in a single thread, you have nothing to worry about.

的静态构造函数创建的每个封闭式运行一次。当封闭式创建和静态构造函数的运行,你可以存储在一个静态的非泛型列表变量的类型。 (你不能用一个通用的静态或者您也可以为每一个密闭型的单独列表)

The static constructor runs once for every closed type that is created. When the closed type is created and the static constructor run, you can store the type in a static non-generic list variable. (You cannot use a generic static or you will have a separate list for every closed type)

public class MyStaticClass
{
    public static List<Type> ClosedTypes = new List<Type>();
}

public class MyGenericType<T>
{
    static MyGenericType()
    {
        MyStaticClass.ClosedTypes.Add(typeof(MyGenericType<T>));
    }
}