C# IsGenericType和IsGenericTypeDefinition之间的区别

C# IsGenericType和IsGenericTypeDefinition之间的区别,c#,generics,reflection,system.type,C#,Generics,Reflection,System.type,Type.IsGenericType和Type.IsGenericTypeDefinition之间有什么区别?有趣的是,MSDN的iGenericTypeDefinition链接被破坏了 在尝试检索给定DbContext中定义的所有dbset之后,我被引导到以下行为,我正在尝试理解这些行为:通过IsGenericType过滤属性会返回所需的结果,而使用IsGenericTypeDefinition则不会(不返回任何结果) 有趣的是,从这篇文章中,我有一个印象,作者确实使用IsGenericTyp

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

在尝试检索给定DbContext中定义的所有dbset之后,我被引导到以下行为,我正在尝试理解这些行为:通过IsGenericType过滤属性会返回所需的结果,而使用IsGenericTypeDefinition则不会(不返回任何结果)

有趣的是,从这篇文章中,我有一个印象,作者确实使用IsGenericTypeDefinition获得了他的数据库集,而我没有

下面是说明讨论的示例:

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; }
}
private static void Main(字符串[]args)
{
A=新的A();
int-propertyCount=a.GetType().GetProperties().Where(p=>p.PropertyType.IsGenericType).Count();
int-propertyCount2=a.GetType().GetProperties().Where(p=>p.PropertyType.IsGenericTypeDefinition).Count();
WriteLine(“count1:{0}count2:{1}”,propertyCount,propertyCount2);
}
//输出:计数1:1计数2:0
公共A类
{
公共字符串aaa{get;set;}
公共列表myList{get;set;}
}

IsGenericType
告诉您,
System.Type
的这个实例表示一个泛型类型,并指定了它的所有类型参数。例如,
List
是泛型类型

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

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

var listInt = typeof(List<int>);
var typeDef = listInt.GetGenericTypeDefinition(); // gives typeof(List<>)

难道你不同意作者使用IsGenericTypeDefinition获取DbSet实例是没有意义的吗?根据您的答案(以及我这边的一些测试),在执行
GetProperties()操作时,您不会将DbSet作为属性返回。其中(p=>p.IsGenericTypeDefinition)
@Veverke您完全正确,答案副本的作者粘贴了OP的代码,但有一个错误。我对答案进行了编辑,非常感谢!换句话说,IsGenericType返回true的类型是“real/complete/usable”泛型类型。IsGenericTypeDefinition为true的类型在代码中还不能真正使用,它是一个泛型类型“blueprint/container”。@Veverke是的,就是这样。某种程度上相关(或者至少……我问这个问题的原因):
var listDef = typeof(List<>);
var listStr = listDef.MakeGenericType(typeof(string));