在抽象类中使用泛型 [英] Using generics in abstract classes
问题描述
我工作的地方实现类需要实现T.名单的问题是,这不起作用抽象类:
I'm working on an abstract class where the implementing class needs to implement a list of T. The problem is that this doesn't work:
public class AbstractClass
{
public int Id { get; set; }
public int Name { get; set; }
public abstract List<T> Items { get; set; }
}
public class Container : AbstractClass
{
public List<Widgets> Items { get; set; }
}
我敢肯定,还有就是我缺少一个明显的答案,我知道我可以建立一个抽象基类将在列表中,但是当我用我的LINQ命令生成列表,抽象型(ItemBase)不与.ToList()方法很好地发挥。就是我想要做如此独特?
I'm sure that there is an obvious answer that I'm missing, and I know that I can build an abstract base type to put in the list, but when I use my Linq command to build the list, the abstract type (ItemBase) doesn't play nicely with the .ToList() method. Is what I'm trying to do so unique?
推荐答案
您需要在类的声明为好,知道什么类型的 T
是:
You need the declaration on the class as well, to know what type T
is:
public abstract class AbstractClass<T>
{
public int Id { get; set; }
public int Name { get; set; }
public abstract List<T> Items { get; set; }
}
public class Container : AbstractClass<Widgets>
{
public List<Widgets> Items { get; set; }
}
您也可以限制哪些T可以,好比说它必须实现的iWidget
:
You can also restrict what T can be, like say it must implement IWidgets
:
public class AbstractClass<T> where T : IWidgets
这篇关于在抽象类中使用泛型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!