开发者

Can i get the generic type of an object?

this is my method: GetListItemsPainted<T>(List<T> list) and i don't know what type is that list开发者_Python百科 of,

how can i create new list that would have the passed list type?

something like this:

List<list.GetType()> newList = new List<list.GetType()>();

how can i cast my list to the real type so i would have all his properties etc.?

thanks


You can create a list using T:

List<T> newList = new List<T>();

If you must get the type, you can use typeof. This is similar to what you asked for, but has other uses, you don't need it to make generics work:

Type myType = typeof(T);


You do not have to create a new List, you already have one.

If you require a specific type, then constrain your generic type parameters with a where constraint

If you intend to react to a wide variety of arbitrary types, which is a bad design decision in my opinion, then you will need to use a conditional with .Cast<T>()

something like:

Type myListType = list.GetType().GetGenericArguments()[0];
// or Type myListType = typeof(T); as stated by Kobi
if(myListType == typeof(SomeArbitraryType))
{
   var typedList = list.Cast<SomeArbitraryType>();
   // do something interesting with your new typed list.
}

But again, I would consider using a constraint.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜