【问题标题】:Generics and Inheritance: How to use the parent in the child class?泛型和继承:如何在子类中使用父类?
【发布时间】:2011-11-17 11:08:07
【问题描述】:

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

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

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

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

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)的父类型,因为子节点也可以是other类型。

现在,我不知道如何实例化 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<???>>();

任何想法,我将如何实施?

提前致谢,
弗兰克

【问题讨论】:

  • 对不起,我没有看到任何可以证明使用泛型的东西。恕我直言,您应该停止担心泛型并重新考虑您的设计。
  • 正如我在第一句话中所说的那样,我正准备重新设计并尝试使用泛型来解决以下问题(只是一个例子):在基类中,有一个方法NodeByName(字符串name) 它从树中给出具有给定名称的节点。现在,返回值始终是基类类型,而不是派生类型。使用泛型,我可以将返回类型定义为 T -> 所以它是正确的继承类型,我不需要强制转换。所以,除了通用的设计重新思考的提示是最受欢迎的;)

标签: c# silverlight generics inheritance architecture


【解决方案1】:

问题是约束。如果您将其更改为,它将起作用

public class ServiceNodeComponent<T> : ServiceNodeBase<ServiceNodeComponent<T>> 
    where T : ServiceNodeBase<T> {

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多