如何从一个普通的名单,LT获得T的类型; T&GT ;? [英] How to get the type of T from a generic List<T>?

查看:92
本文介绍了如何从一个普通的名单,LT获得T的类型; T&GT ;?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让说我有一个列表< T> ABC =新的List< T&GT ;; A类中公共类MyClass的< T> // ...

Let say I have a List<T> abc = new List<T>; inside a class public class MyClass<T>//....

后来,当我初始化类中, T 变成 MyTypeObject1 。所以我有一个通用的列表,名单,LT; MyTypeObject1&GT;

Later, when I initialize the class, the T becomes MyTypeObject1. So I have a generic list, List< MyTypeObject1 >.

我想知道,我的班级列表中包含什么类型的对象,例如名为 ABC 列表中包含什么类型的对象?

I would like to know, what type of object the list of my class contain, e.g. the list called abc contain what type of object?

我做不到 ABC [0] .GetType(); 因为列表可能包含零元素。我该怎么办呢?

I cannot do abc[0].GetType(); because the list might contain zero elements. How can I do it?

推荐答案

如果我理解正确,你的列表中有相同类型的参数作为容器类本身。如果是这种情况,则:

If I understand correctly, your list has the same type parameter as the container class itself. If this is the case, then:

Type typeParameterType = typeof(T);

如果你是在具有幸运形势对象作为一个类型参数,见马克的回答。

If you are in the lucky situation of having object as a type parameter, see Marc's answer.

这篇关于如何从一个普通的名单,LT获得T的类型; T&GT ;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆