简体   繁体   English

由派生类定义的基类集合

[英]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. 我在C#中的经验并不像我在C ++中那么接近,但试图变得更好。

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? 在C#中,是否存在一种创建包含属性的基类的方法,该属性是List,然后在派生类中定义该具体类型的T是什么?

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? 我想不会,因为你不能再对基类中的接口起作用,因为在你知道实际实例是什么类型之前你不知道你得到了什么类型,但也许在C#中有一些神奇的东西是类似的这个?

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: 然后在创建派生类时,可以像这样指定T

public class Derived : Base<Elephant>
{

}

For the consumers of Derived , the type of the Data property is List<Elephant> . 对于Derived的使用者, Data属性的类型是List<Elephant>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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