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
445 views
in Technique[技术] by (71.8m points)

c# 4.0 - Collection of derived classes that have generic base class

Say I have several derived classes whose base class is a generic class. Each derived class inherit the base class with a specific type override(but all types are also derived from a single base type).

For example:

I have a base row class

class RowBase
{
    //some properties and abstract methods
}

And I have two specific row classes that are derived from the row base class

class SpecificRow1 : RowBase
{
    //some extra properties and overrides
}

class SpecificRow2 : RowBase
{
    //some extra properties and overrides
}

Then I have a second base class that is a generic class which contains a collection of derived classes from RowBase

class SomeBase<T> where T : RowBase
{
    ICollection<T> Collection { get; set; }
    //some other properties and abstract methods
}

Then I have two classes that derive from SomeBase but are using different specific row class

class SomeClass1 : SomeBase<SpecificRow1>
{
     //some properties and overrides
}

class SomeClass2 : SomeBase<SpecificRow2>
{
     //some properties and overrides
}

Now that in my main or a bigger scope, I want to create a list/collection that consist both SomeClass1 and SomeClass2 objects. Like

ICollection<???> CombinedCollection = new ...
CombinedCollection.Add(new SomeClass1())
CombinedCollection.Add(new SomeClass2())
.
.
.
//add more objects and do something about the collection
.
.
.

The question is: is it possible to have such collection? If it is possible, how can I achieve this? If no, what can be an alternative way?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

This can be done with the help of Covariance and Contravariance.

Add a new interface that and make the T parameter covariant (using the out keyword):

interface ISomeRow<out T> where T : RowBase
{
}

SomeBase should inherit that interface like this:

class SomeBase<T> : ISomeRow<T> where T : RowBase
{
    //some other properties and abstract methods
}

Then, the following will work:

List<ISomeRow<RowBase>> myList = new List<ISomeRow<RowBase>>();
myList.Add(new SomeClass1());
myList.Add(new SomeClass2());

Hope this is what you're looking for :)


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

...