首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >泛型和继承:如何在子类中使用父类?

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

Stack Overflow用户
提问于 2011-11-17 11:08:07
回答 1查看 208关注 0票数 0

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

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

代码语言:javascript
复制
public abstract class BaseNode<T> : INotifyPropertyChanged where T: BaseNode<T>
{
  protected ObservableCollection<T> _children;
  ...
}

其次,我添加了一个继承自BaseNode的类,它是all my的基础:

代码语言:javascript
复制
public class ServiceNodeBase<T> : BaseNode<ServiceNodeBase<T>> where T : ServiceNodeBase<T>
{
  public string Description { get; set; }
  ...
}

最后,由于我可以有两种不同的节点,所以我为每种节点创建了一个类,即:

代码语言:javascript
复制
public class ServiceNodeComponent<T> : ServiceNodeBase<ServiceNodeComponent<T>> where T : ServiceNodeComponent<T>
{
  public HashSet<Attributes> Attributes { get; set; }
  ...
}

ServiceNodeComponent,中,我需要一个扫描树的方法,即获取属于ServiceNodeComponent.类型的所有子节点解析树时,我需要使用ServiceNodeComponent (ServiceNodeBase)的父类型,因为子节点也可以是其他类型。

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

代码语言:javascript
复制
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<???>>();

有什么想法吗,我会如何实现这一点?

提前谢谢你,

弗兰克

EN

回答 1

Stack Overflow用户

发布于 2011-11-17 14:27:21

问题在于约束。如果你把它改为

代码语言:javascript
复制
public class ServiceNodeComponent<T> : ServiceNodeBase<ServiceNodeComponent<T>> 
    where T : ServiceNodeBase<T> {

    public HashSet<ServiceNodeComponent<T>> GetAllChildComponents() {
        // ...
        HashSet<ServiceNodeBase<T>> workingList = new HashSet<ServiceNodeBase<T>>();
        // ...
    }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/8166090

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档