Evg*_*raf 5 c# generics collections
我有我的实体的基类
public class Entity<T> where T : Entity<T>, new()
{
public XElement ToXElement()
{
}
public static T FromXElement(XElement x)
{
}
}
Run Code Online (Sandbox Code Playgroud)
我必须使用这种奇怪的结构Entity<T> where T : Entity<T>,因为我希望静态方法FromXElement是强类型的另外,我有一些实体,像那样
public class Category : Entity<Category>
{
}
public class Collection : Entity<Collection>
{
}
Run Code Online (Sandbox Code Playgroud)
如何使用基类创建我的实体的通用列表?
var list = new List<Entity<?>>();
list.Add(new Category());
list.Add(new Collection());
Run Code Online (Sandbox Code Playgroud)
你不能用这个定义。Category和之间没有“公共基类” (当然, Collection除了)。object
如果有,假设Entity<T>定义为:
public class Entity
{
}
public class Entity<T> : Entity where T : Entity<T>, new()
{
public XElement ToXElement()
{
}
public static T FromXElement(XElement x)
{
}
}
Run Code Online (Sandbox Code Playgroud)
那么你可以做
var list = new List<Entity>();
list.Add(new Category());
list.Add(new Collection());
Run Code Online (Sandbox Code Playgroud)
但这会给你带来什么?