更改继承属性的类型(更改为继承类型)
使用 C# 我有一个类,其中包含有向图的根节点等元信息。我们将其称为容器类。该容器可以以两种不同的模式出现:编辑器模式和配置器模式。根据模式的不同,根节点具有不同的类型NodeEdit或NodeConfig,两者都继承自同一子类。
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-property 的类型为 节点编辑器。 我可以在 setter 中检查这一点并拒绝除 NodeEditor 类型之外的所有节点,但我希望该属性属于特定类型,以便我可以在编译时检测到错误的分配。
预先感谢,
坦率
using C# I have a class which contains among other meta information the root node of a directed graph. Let's call this the Container-Class. This container can appear in two different modes, Editor-Mode and Configurator-Mode. Depending on the mode, the root-node is of a different type NodeEdit or NodeConfig, both inheriting from the same subclass.
public abstract class NodeBase
{
string Name { get; set; }
...
}
public class NodeEdit : NodeBase ...
public class NodeConfig : NodeBase ...
For the container, I also create a base class and inherit from it:
public abstract class ContainerBase
{
NodeBase Root { get; set; }
...
}
When creating the classes for Editor- and Configuratorcontainer by inheriting from ContainerBase, I want to become the type of the Root - property the specific (inherited from NodeBase) type like:
public class ContainerEditor : ContainerBase
{
NodeEditor Root { get; set; }
...
}
But I cannot change the type of a property defined in ContainerBase. Is there a way to solve this problem? I can use the BaseNode-type, and add an element of NodeEditor like
ContainerEditorInstance.Root = new NodeEditor();
because the type NodeEditor is inherited from type BaseEditor, but in the Container-Editor class, I want to explicitly only allow the type of the Root-property to be NodeEditor.
I could check this in the setter and reject all nodes but those of type NodeEditor, but I'd like to have the property be of the specific type, so I can detect wrong assignments at compile-time.
Thanks in advance,
Frank
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
使用泛型:
Use generics:
您可以重新声明它:
You can redeclare it:
您可以使容器基类通用:
在派生类中指定类型:
You can make the container base generic:
In the derived class you specify the type:
我想这里一个好的解决方案是泛型。所以你会写这样的东西:
I suppose a good solution here will be Generics. So you'd write something like this: