在抽象类中使用泛型 [英] 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 命令构建列表时,抽象type (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 override List<Widgets> Items { get; set; }
}
你也可以限制 T 可以是什么,比如说它必须实现 IWidgets
:
You can also restrict what T can be, like say it must implement IWidgets
:
public class AbstractClass<T> where T : IWidgets
这篇关于在抽象类中使用泛型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!