Type中的3个bool属性: IsGenericType , IsGenericTypeDefinition , IsGenericParameter 标签: 泛型TypeC# 2015-05-20



  • 首先说下 IsGenericType 
    用3个实例说明:
   typeof(DateTime).IsGenericType : false
   typeof(List<int>).IsGenericType: true
   typeof(Dictionary<,>).IsGenericType:true
   
   
  • 1
  • 2
  • 3
  • 1
  • 2
  • 3

类型如果是泛型则为 true 
但是要注意以下情况: 
T[], List[] 等等数组时, IsGenericType为False 
typeof(T[]).GetElementType().IsGenericType才是True


  • 接着说 IsGenericTypeDefinition 
    用2个实例说明:
   typeof(List<int>).IsGenericTypeDefintion : false
   typeof(List<>).IsGenericTypeDefinition :true
   
   
  • 1
  • 2
  • 1
  • 2

IsGenericTypeDefinition : 获取一个值,该值指示当前 Type 是否表示可以用来构造其他泛型类型的泛型类型定义。 
也就是说表明 这个 type 是否可以用于构建泛型定义 
比如 List<> 可以通过反射构建出 List,List 
例子:

var typeList = typeof(List<>);        
Type typeDataList = typeList.MakeGenericType( typeof(DateTime)); //通过List<>构建出List<DateTime>
   
   
  • 1
  • 2
  • 1
  • 2

  • 最后说下 IsGenericParameter 
    这个Property用于表明当前类型是一个T类型 
    例如:
    typeof(List<>).GetGenericArguments()
返回: new Type[]{ typeof(T) }
此时: 
        typeof(T).IsGenericParameter == True
        typeof(T).GenericParameterPosition  == 0    
   
   
  • 1
  • 2
  • 3
  • 4
  • 5
  • 1
  • 2
  • 3
  • 4
  • 5

对比:

 typeof(List<DateTime>).GetGenericArguments()
返回: new Type[]{ typeof(DateTime) }
此时: 
    typeof(DateTime).IsGenericParameter  == False
    typeof(DateTime).GenericParameterPosition    : throw exception
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值