Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
266 views
in Technique[技术] by (71.8m points)

c# - How do I create a list of objects that inherit from the same generic class with varying types?

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>
{ ... }

...

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.

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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...