问题描述
Type.IsGenericType
和Type.IsGenericTypeDefinition
有什么区别?有趣的是,用于IsGenericTypeDefinition的MSDN链接已断开.
What is the difference between Type.IsGenericType
and Type.IsGenericTypeDefinition
? Interestingly enough, MSDN's link for IsGenericTypeDefinition is broken.
在尝试检索给定DbContext中定义的所有DbSet之后,我得到了以下结果,这是我试图理解的行为:通过IsGenericType筛选属性返回所需的结果,而使用IsGenericTypeDefinition则不会(不会不返回任何内容.)
After playing a bit with trying to retrieve all the DbSets defined in a given DbContext, I was lead to the following, which behavior I am trying to understand: filtering properties via IsGenericType returns the desired results, while with IsGenericTypeDefinition not (does not return any).
有趣的是,从这篇帖子中,我的印象是作者确实得到了他的DbSet使用IsGenericTypeDefinition,而我没有.
It's interesting that from this post I have the impression that the author did get his DbSets using IsGenericTypeDefinition, while I did not.
以下示例说明了该讨论:
Follows a sample that illustrates the discussion:
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; }
}
推荐答案
IsGenericType
告诉您System.Type
的此实例表示具有指定的所有类型参数的泛型类型.例如,List<int>
是通用类型.
IsGenericType
tells you that this instance of System.Type
represents a generic type with all its type parameters specified. For example, List<int>
is a generic type.
IsGenericTypeDefinition
告诉您System.Type
的此实例表示一个定义,可以通过为其类型参数提供类型参数来构造泛型类型.例如,List<>
是通用类型定义.
IsGenericTypeDefinition
, on the other hand, tells you that this instance of System.Type
represents a definition from which generic types can be constructed by supplying type arguments for its type parameters. For example, List<>
is a generic type definition.
您可以通过调用GetGenericTypeDefinition
来获得通用类型的通用类型定义:
You can get a generic type definition of a generic type by calling GetGenericTypeDefinition
:
var listInt = typeof(List<int>);
var typeDef = listInt.GetGenericTypeDefinition(); // gives typeof(List<>)
您可以通过为通用类型定义提供MakeGenericType
的类型参数来从通用类型定义中创建通用类型:
You can make a generic type from a generic type definition by providing it with type arguments to MakeGenericType
:
var listDef = typeof(List<>);
var listStr = listDef.MakeGenericType(typeof(string));
这篇关于IsGenericType和IsGenericTypeDefinition之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!