开发者

Is there a way to get the type of the objects stored in a generic list?

Given a generic list of type List<T> how do I find type开发者_开发知识库 T?

I suppose if the list is populated I could take listInstance[0].GetType() but that seems a bit hackish.

Edit:

For context, I want to populate a DataTable with columns based on the Properties of an object. Where an object property is a generic list I want to add a column for each property of the object stored by the list. I'll flatten the data structure to fit into a DataRow later.

The reason I don't want to use the type of the first object in the list is because it's not guaranteed that every instance will have the list populated. Some will and some won't, but I'll still need all the columns ahead of time.


You could try

typeof(List<T>).GetGenericArguments()[0]

This works with an empty array, while your version does not.

UPDATE:

On an instance use

instance.GetType().GetGenericArguments()[0]


Why is that hackish?, is not hackish at all. That is why the GetType() method exits. To obtain the type of the object.


You can use

 myList.GetType().GetGenericArguments()

This returns an array of all the types specified in the declaration of the object.


It is hackish because if the list isn't populated, you can't get an answer.

You'll need to reflect against the Type:

List<int> mylist = new List<int>();
Type listType = mylist.GetType();
Type genericType = listType.GetGenericArguments()[0];


Do it as you said. It is not hackish.

You can also call GetType() directly on your list and use it to look at type of its its T.


You could also do listInstance[0] is SomeTypeIExpectThisToBe if you are expecting a type and want to do something because of that


You should have access to the type parameter, so you can use typeof:

void ProcessList<T>( List<T> listInstance)
{
    Type type = typeof(T);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜