【发布时间】:2011-05-07 09:37:27
【问题描述】:
我想创建一个可扩展的嵌套结构,看起来我应该能够使用泛型来做到这一点,尽管我可能没有“正确”使用它们。
我希望能够从 GroupType 和/或 OptionType 创建子类。问题是我无法对泛型类型执行new 操作,即使我指定它们只能是某个基本类型。
有什么办法可以做我想做的事吗?
public class AllInfo<GroupType, OptionType>
where GroupType: GroupBase<OptionType>
where OptionType: OptionBase
{
public List<string> Names { set; get; }
public List<GroupType> Groups { set; get; }
public AllInfo()
{
DataSet ds = DatabaseRetreival();
this.Groups.add(new GroupType(ds["Name"], ds["Type"]));
}
}
public class GroupBase<OptionType>
where OptionType: OptionBase
{
public string Name { set; get; }
public string Type { set; get; }
public List<OptionType> Options { set; get; }
public GroupBase(string name, string type)
{
this.Name = name;
this.Type = type;
DataSet ds = DatabaseRetreival(this.Type);
this.Options.Add(new OptionType(ds["Name"]));
}
}
public class OptionBase
{
public string Name { set; get; }
public OptionBase(string name)
{
this.Name = name;
}
}
【问题讨论】:
标签: c# generics inheritance polymorphism