如何从泛型类或方法的成员中获取T的类型?假设我在类或方法中有一个泛型成员,那么:public class Foo<T>{
public List<T> Bar { get; set; }
public void Baz()
{
// get type of T
} }当我实例化类时,T成MyTypeObject1,因此该类具有一个泛型List属性:List<MyTypeObject1>..这同样适用于非泛型类中的泛型方法:public class Foo{
public void Bar<T>()
{
var baz = new List<T>();
// get type of T
}}我想知道,我的类的列表包含什么类型的对象。因此,List属性调用Bar或者局部变量baz,包含哪种类型的T?我做不到Bar[0].GetType(),因为列表可能包含零元素。我该怎么做?
3 回答
慕沐林林
TA贡献2016条经验 获得超9个赞
objectIList
List<T>
Type type = abc.GetType().GetGenericArguments()[0];
Type type = abc.GetType().GetProperty("Item").PropertyType;using System.Reflection;// ...var type = abc.GetType().GetTypeInfo().GenericTypeArguments[0];
ITMISS
TA贡献1871条经验 获得超8个赞
public static Type GetListType<T>(this List<T> _){
return typeof(T);}public static Type GetEnumeratedType<T>(this IEnumerable<T> _){
return typeof(T);}List<string> list = new List<string> { "a", "b", "c" };
IEnumerable<string> strings = list;IEnumerable<object> objects = list;
Type listType = list.GetListType();
// stringType stringsType = strings.GetEnumeratedType();
// stringType objectsType = objects.GetEnumeratedType(); // BEWARE: object- 3 回答
- 0 关注
- 1522 浏览
添加回答
举报
0/150
提交
取消
