簡體   English   中英

更改繼承屬性的類型(更改為繼承類型)

[英]Changing the Type of a inherited property (to a inherited type)

使用C#,我有一個包含除其他元信息之外的有向圖的根節點的類。 我們稱其為Container-Class 該容器可以以兩種不同的模式出現,編輯器模式和配置器模式。 根據模式的不同,根節點的類型為NodeEditNodeConfig ,它們均繼承自同一子類。

public abstract class NodeBase
{
  string Name { get; set; }
  ...
}

public class NodeEdit : NodeBase ...
public class NodeConfig : NodeBase ...

對於容器,我還創建了一個基類並從中繼承:

public abstract class ContainerBase
{
  NodeBase Root { get; set; }
  ...
}

當通過從ContainerBase繼承為Editor-和Configuratorcontainer創建類時,我想成為Root-屬性的類型,該特定類型(從NodeBase繼承)的類型如下:

public class ContainerEditor : ContainerBase
{
  NodeEditor Root { get; set; }
  ...
}

但是我無法更改ContainerBase中定義的屬性的類型。 有辦法解決這個問題嗎? 我可以使用BaseNode類型,並添加NodeEditor的元素,例如

ContainerEditorInstance.Root = new NodeEditor();

因為類型NodeEditor是從類型BaseEditor繼承的,但是在Container-Editor類中,我想顯式地僅將Root屬性的類型設置為NodeEditor 我可以在設置器中進行檢查,並拒絕除NodeEditor類型之外的所有節點,但是我希望該屬性為特定類型,因此可以在編譯時檢測到錯誤的分配。

提前致謝,
坦率

使用泛型:

public abstract class ContainerBase<T> where T:NodeBase
{
  T Root { get; set; }
  ...
}

public class ContainerEditor : ContainerBase<NodeEditor>
{      
  ...
}

您可以重新聲明:

public class ContainerEditor : ContainerBase
{
  public NodeEditor Root {
    get { return (NodeEditor)base.Root; }
    set { base.Root = value; }
  }
  ...
}

您可以使容器基類通用:

public abstract class ContainerBase<TRoot> where TRoot : NodeBase
{
  TRoot Root { get; set; }
  ...
}

在派生類中,指定類型:

public class ContainerEditor : ContainerBase<NodeEditor>
{
  ...
}

我想仿制葯是一個很好的解決方案。 所以你會寫這樣的東西:

public class ContainerEditor<T>:ContainerBase
{
    T Root {get;set;}
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM