c# 判断 泛型t 类型_C#泛型列表<T>如何获取T的类型?

我正在做一个反思项目,现在被困了。如果我有一个可以容纳列表的“ myclass”对象,如果myclass.SomList属性为空,是否有人知道如何获取以下代码中的类型?

List  myList  =  dataGenerator.getMyClasses();

lbxObjects.ItemsSource = myList;

lbxObjects.SelectionChanged += lbxObjects_SelectionChanged;

private void lbxObjects_SelectionChanged(object sender, SelectionChangedEventArgs e)

{

Reflect();

}

Private void Reflect()

{

foreach (PropertyInfo pi in lbxObjects.SelectedItem.GetType().GetProperties())

{

switch (pi.PropertyType.Name.ToLower())

{

case "list`1":

{

// This works if the List contains one or more elements.

Type tTemp = GetGenericType(pi.GetValue(lbxObjects.SelectedItem, null));

// but how is it possible to get the Type if the value is null?

// I need to be able to create a new object of the type the generic list expect.

// Type type = pi.getType?? // how to get the Type of the class inside List?

break;

}

}

}

}

private Type GetGenericType(object obj)

{

if (obj != null)

{

Type t = obj.GetType();

if (t.IsGenericType)

{

Type[] at = t.GetGenericArguments();

t = at.First();

} return t;

}

else

{

return null;

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值