泛型和继承:如何在子类中使用父类?

时间:2011-11-17 11:08:07

标签: c# silverlight generics inheritance architecture

我只是尝试重新设计我的Silverlight-4应用程序并尝试使用泛型。

简单地说,我有一棵树,可以包含两种类型的节点。作为基类,我创建了一个完成所有“组织”的类,比如有一个子项列表,父项,添加子项的方法等等:

public abstract class BaseNode<T> : INotifyPropertyChanged where T: BaseNode<T>
{
  protected ObservableCollection<T> _children;
  ...
}

其次,我添加了一个继承自BaseNode的类,并且是所有我的treenodes的基础:

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 中,我需要一个方法,它扫描树,即获取Type ServiceNodeComponent 的所有子节点。解析树时,我需要使用父类型的ServiceNodeComponent(ServiceNodeBase),因为子节点也可以是其他类型。

现在,我不知道如何实例化ServiceNodeBase-Variable。

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<???>>();

任何想法,我将如何实现这一点?

提前致谢,
弗兰克

1 个答案:

答案 0 :(得分:0)

问题在于约束。如果将其更改为

,它将起作用
public class ServiceNodeComponent<T> : ServiceNodeBase<ServiceNodeComponent<T>> 
    where T : ServiceNodeBase<T> {

    public HashSet<ServiceNodeComponent<T>> GetAllChildComponents() {
        // ...
        HashSet<ServiceNodeBase<T>> workingList = new HashSet<ServiceNodeBase<T>>();
        // ...
    }
}