问题描述
我和关闭试图找到一个答案,这个花了几个小时,我可能有问题正确地措辞的麻烦,这不利于。从本质上讲,我有一个抽象类:
I've spent a few hours on and off trying to find an answer to this, I'm probably having trouble with wording the question correctly, which doesn't help. Essentially, I have an abstract class:
public abstract class GenericType<T>
{ ... }
和一堆,从它继承的类:
And a bunch of classes that inherit from it:
public class AType: GenericType<A>
{ ... }
public class BType: GenericType<B>
{ ... }
...
最后,我有希望遏制,从GenericType继承的事情的清单另一个类,无论T,即Atypes,BTypes等的价值。
Lastly, I have another class that wants to contain a list of things that inherit from GenericType, regardless of the value of T, i.e. Atypes, BTypes and so on.
我的第一个尝试均使用列表< GenericType>
和列表< GenericType<对象>>
但niether的给我任何的喜悦。
My first attempts were to use List<GenericType>
and List<GenericType<Object>>
but niether's given me any joy.
这是我应该怎么会对此有什么建议? !不胜感谢
Any tips on how I should be going about this? Much thanks!
推荐答案
所以,如果我理解正确的话,你想是这样的:
So, if I understand correctly, you want something like this:
List<GenericType>
可以包含 ATYPE
的任何实例, B型
等,您只需通过这样做 GenericType< T>
本身的一个子类GenericType
:
Which can contain any instance of AType
, BType
, etc. You simply do this by making GenericType<T>
itself a subclass of GenericType
:
public class GenericType { }
public class GenericType<T> : GenericType { }
public class AType : GenericType<int> { }
public class BType : GenericType<int> { }
您可以再坚持任何实例成列表< GenericType>
。
You can then stick any instance into a List<GenericType>
.
这篇关于我如何创建一个从具有不同类型相同的通用类继承对象的列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!