简体   繁体   English

VB.Net - 我如何获得List中包含的对象的类型

[英]VB.Net - how can i get the type of the object contained in an List

If I have a list... 如果我有一个清单......

dim l as List(of MyClass) = new List(of MyClass)

and I want to get the type of the objects contained in the list, how do I do that? 我想获取列表中包含的对象的类型,我该怎么做?

The obvious answer, that doesn't seem to be possible from my actual implementation, would be to do something like this... 显而易见的答案,从我的实际实施似乎不可能,将做这样的事情......

public function GetType(byval AList as IList(of GenericType)) as System.Type
  dim lResult as system.type = nothing
  if AList.Count > 0 then lResult = AList(0).GetType
  return lResult
end function

But what if the list is empty and I still want to know the type it contains? 但是如果列表是空的并且我仍然想知道它包含的类型怎么办?

There's a good article on this at MSDN, here 这里有一篇关于MSDN的好文章

Basically you can use GetGenericArguments() to get an array of the types provided as arguments to your generic type. 基本上,您可以使用GetGenericArguments()来获取作为泛型类型的参数提供的类型数组。 In the case of a List, there's only one argument so you will get what you need using eg 在List的情况下,只有一个参数,所以你将得到你需要的东西,例如

dim l as List(of MyClass) = new List(of MyClass)
dim t as Type = (l.GetGenericArguments())(0)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM