gpt4 book ai didi

c# - 创建泛型列表

转载 作者:太空狗 更新时间:2023-10-29 23:09:11 24 4
gpt4 key购买 nike

我有我的实体的基类

public class Entity<T> where T : Entity<T>, new()
{
public XElement ToXElement()
{
}
public static T FromXElement(XElement x)
{
}
}

我必须使用这个奇怪的结构 Entity<T> where T : Entity<T> ,因为我希望静态方法 FromXElement 是强类型的另外,我有一些实体,比如

public class Category : Entity<Category>
{
}
public class Collection : Entity<Collection>
{
}

我如何使用基类创建我的实体的通用列表?

var list = new List<Entity<?>>();
list.Add(new Category());
list.Add(new Collection());

最佳答案

你不能用那个定义。 Category 之间没有“公共(public)基类”和 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)
{
}
}

那么你可以做

var list = new List<Entity>();
list.Add(new Category());
list.Add(new Collection());

但这会给你带来什么?

关于c# - 创建泛型列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12827023/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com