我只是尝试重新设计我的Silverlight-4应用程序,并尝试了一些泛型。
简单地说,我有一棵树,它可以包含两种节点类型。作为一个基类,我创建了一个执行所有“组织”的类,比如有一个子类列表、一个父类、一个添加子类的方法等等:
public abstract class BaseNode<T> : INotifyPropertyChanged where T: BaseNode<T>
{
protected ObservableCollection<T> _children;
...
}其次,我添加了一个继承自BaseNode的类,它是all my的基础:
public class ServiceNodeBase<T> : BaseNode<ServiceNodeBase<T>> where T : ServiceNodeBase<T>
{
public string Description { get; set; }
...
}最后,由于我可以有两种不同的节点,所以我为每种节点创建了一个类,即:
public class ServiceNodeComponent<T> : ServiceNodeBase<ServiceNodeComponent<T>> where T : ServiceNodeComponent<T>
{
public HashSet<Attributes> Attributes { get; set; }
...
}在ServiceNodeComponent,中,我需要一个扫描树的方法,即获取属于ServiceNodeComponent.类型的所有子节点解析树时,我需要使用ServiceNodeComponent (ServiceNodeBase)的父类型,因为子节点也可以是其他类型。
现在,我不知道如何实例化ServiceNodeBase-变量。
public HashSet<ServiceNodeComponent<T>> GetAllChildComponents()
{
// declaring the container for the found Components is no problem
HashSet<ServiceNodeComponent<T>> resultList = new HashSet<ServiceNodeComponent<T>>();
// but now: how to declare the container for the ServiceBaseNodes?
HashSet<ServiceNodeBase<???>> workingList = new HashSet<ServiceNodeBase<???>>();有什么想法吗,我会如何实现这一点?
提前谢谢你,
弗兰克
发布于 2011-11-17 14:27:21
问题在于约束。如果你把它改为
public class ServiceNodeComponent<T> : ServiceNodeBase<ServiceNodeComponent<T>>
where T : ServiceNodeBase<T> {
public HashSet<ServiceNodeComponent<T>> GetAllChildComponents() {
// ...
HashSet<ServiceNodeBase<T>> workingList = new HashSet<ServiceNodeBase<T>>();
// ...
}
}https://stackoverflow.com/questions/8166090
复制相似问题