Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
674 views
in Technique[技术] by (71.8m points)

collections - C# - Get the item type for a generic list

What would be the best way of getting the type of items a generic list contains? It's easy enough to grab the first item in the collection and call .GetType(), but I can't always be sure there will be an item in the collection.

Hope that makes sense.

Thanks,
Sonny

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You could use the Type.GetGenericArguments method for this purpose.

List<Foo> myList = ...

Type myListElementType = myList.GetType().GetGenericArguments().Single();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...