反射:通用列表的非通用子类中包含的项目类型
public class MyList : List<MyClass>
如果我有一个包含 MyList
实例的 object
,如何通过反射获取类型 MyClass
?该列表可以为空,因此我无法执行诸如 myList[0].GetType()
之类的操作。
ps 我不能停止使用 MyList
并直接使用泛型 List (情况稍微复杂一点,并且有“隐藏”泛型参数的原因),所以我不能通过 GetGenericArguments()
获取 MyClass
。
public class MyList : List<MyClass>
How can I get the type MyClass
through reflection if I have an object
that contains an instance of MyList
? The list can be empty, so I can't do something like myList[0].GetType()
.
p.s. I can't just stop using MyList
and directly use the generic List instead (the situation is a bit more complicated, and there are reasons for "hiding" the generic argument), so I can't pick up MyClass
through GetGenericArguments()
.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我使用
IList
而不是列表。这个比较通用。然而,实现多个ILis
版本(例如IList
和IList
)的类型也发生了变化。 )。I use
IList<T>
instead of list. This is more generic. However, there is also the change of a type implementing multipleILis<T>
versions (such asIList<string>
andIList<int>
).您可以获得基本类型,即
List
;从中您可以使用 GetGenericArguments 获取通用类型参数。You can get the base type, which will be
List<MyClass>
; from it you can get the generic type argument with GetGenericArguments.你的类实现了通用接口吗?您可以使用以下代码:
如果没有接口,您可以尝试以下操作:
Is your class implements generic interfaces? you can use the following code:
Without interfaces you can try the following: