How do I create a generic List of objects that are constrained to inherit from the same generic class constructed with different type arguments?
That's not possible in the C# type system; you can only make a list of an actual type, not of a "type pattern" like "List<U>
where U must be Foo<T>
for some unspecified T".
To see why it is impossible, let's hypothetically suppose that it was possible. We'll annotate the "type pattern" as a question mark:
class Stack<T> { ... }
...
List<Stack<?>> listOfStacks = new List<Stack<?>>();
listOfStacks.Add(new Stack<int>());
listOfStacks.Add(new Stack<Giraffe>());
Ok, great. Now what are you going to do with the list of stacks? You can't safely do anything with the stack that involves the type parameter of the stack:
listOfStacks[0].Push("hello");
That should fail at compile time because the stack in slot zero is a stack of ints, not strings. How can the compiler know that? The compiler cannot know that. By allowing this feature, you essentially break the ability of the compiler to type-check your program.
To answer "how do I do this thing which is impossible?" it is helpful to know why you want to do the impossible thing. Instead of trying to do this impossible thing tell us what you are really trying to do and see if anyone can solve the real problem.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…