IsGenericType和IsGenericTypeDefinition之间的区别

Vev*_*rke 14 c# generics reflection system.type

Type.IsGenericType和之间有什么区别Type.IsGenericTypeDefinition?有趣的是,MSDN的IsGenericTypeDefinition链接已被破坏.

在尝试检索给定DbContext中定义的所有DbSets后,我发现了以下内容,我试图理解这种行为:通过IsGenericType过滤属性返回所需的结果,而不使用IsGenericTypeDefinition(不返回任何).

有趣的是,从这篇文章中我得到的印象是作者使用IsGenericTypeDefinition获得了他的DbSets,而我却没有.

按照说明讨论的示例:

private static void Main(string[] args)
{
    A a = new A();
    int propertyCount = a.GetType().GetProperties().Where(p => p.PropertyType.IsGenericType).Count();
    int propertyCount2 = a.GetType().GetProperties().Where(p => p.PropertyType.IsGenericTypeDefinition).Count();

    Console.WriteLine("count1: {0}  count2: {1}", propertyCount, propertyCount2);
}

// Output: count1: 1  count2: 0

public class A
{
    public string aaa { get; set; }
    public List<int> myList { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

das*_*ght 30

IsGenericType告诉您此实例System.Type表示一个泛型类型,其中指定了所有类型参数.例如,List<int>是通用类型.

IsGenericTypeDefinition另一方面,它告诉您这个实例System.Type表示一个定义,通过为其类型参数提供类型参数,可以从中构造泛型类型.例如,List<>是泛型类型定义.

您可以通过调用获取泛型类型的泛型类型定义 GetGenericTypeDefinition以下:

var listInt = typeof(List<int>);
var typeDef = listInt.GetGenericTypeDefinition(); // gives typeof(List<>)
Run Code Online (Sandbox Code Playgroud)

您可以通过为其提供类型参数,从泛型类型定义中创建泛型类型 MakeGenericType:

var listDef = typeof(List<>);
var listStr = listDef.MakeGenericType(typeof(string));
Run Code Online (Sandbox Code Playgroud)

  • 换句话说,IsGenericType返回true的类型是"真实/完整/可用"泛型类型.IsGenericTypeDefinition为true的类型在代码中实际上不可用,它是泛型类型"blueprint/container". (2认同)