How to create a list of objects that inherit from the same generic class with different types?

I spent several hours trying to find the answer to this question, I probably have problems with the correct wording of the question, which does not 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>
{ ... }

...

Finally, 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, etc.

My first attempts were to use List<GenericType>and List<GenericType<Object>>, but niether gave me any joy.

Any tips on how I should do this? Many thanks!

+3
source share
4

, , - :

List<GenericType>

AType, BType .. , GenericType<T> GenericType:

public class GenericType { }
public class GenericType<T> : GenericType { }
public class AType : GenericType<int> { }
public class BType : GenericType<int> { }

List<GenericType>.

+8

, , ?

#; , " ", "List<U>, U Foo<T> T".

, , , , . " " :

class Stack<T> { ... }
...
List<Stack<?>> listOfStacks = new List<Stack<?>>();
listOfStacks.Add(new Stack<int>());
listOfStacks.Add(new Stack<Giraffe>());

, . , ? , :

listOfStacks[0].Push("hello");

, zero ints, . ? . , .

" , ?" , . , , , , - .

+10

GenericType<T> IAmNotGeneric, AType BType List<IAmNotGeneric>.

public abstract class GenericType<T> : IAmNotGeneric

.

public abstract class GenericType<T> : NonGenericType
+3

?

Assembly.GetExecutingAssembly().GetTypes
    .Where(type => type.BaseType.IsGenericType && type.BaseType.GetGenericTypeDefinition() == typeof(GenericType<>))
    .ToList().
    .ForEach(type => list.Add(Activator.CreateInstance(type)));
0

All Articles