简体   繁体   中英

base class collection defined by derived class

I'm not even close to as experienced in C# as I am in C++, but trying to get better.

In C#, does there exist a way to create a base class that contains a property which is a List and then in the derived class define what T is for that concrete type?

public class Base
{
    public List<T> Data { get; set; }
}

public class Derived : Base
{
    // Declare to the world you use Base.data<Elephant>
    // Callers of my Data property get Elephants
}

I imagine not, since you can no longer act on the interface in the base class since you wouldn't know what type you are getting until you know what type the actual instance is, but maybe there is some magical thing in C# that is similar to this?

You can make the base class generic like this:

public class Base<T>
{
    public List<T> Data { get; set; }
}

And then when you create the derived class, you can specify T like this:

public class Derived : Base<Elephant>
{

}

For the consumers of Derived , the type of the Data property is List<Elephant> .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM