如何在不了解实现的情况下在抽象类中创建对象?
有没有办法实现下面我的库摘要中的“CreateNode”方法?或者这只能在库外部的客户端代码中完成?我当前收到错误“无法创建抽象类或接口‘ToplogyLibrary.AbstractNode’的实例”
public abstract class AbstractTopology<T>
{
// Properties
public Dictionary<T, AbstractNode<T>> Nodes { get; private set; }
public List<AbstractRelationship<T>> Relationships { get; private set; }
// Constructors
protected AbstractTopology()
{
Nodes = new Dictionary<T, AbstractNode<T>>();
}
// Methods
public AbstractNode<T> CreateNode()
{
var node = new AbstractNode<T>(); // ** Does not work **
Nodes.Add(node.Key, node);
}
}
}
public abstract class AbstractNode<T>
{
public T Key { get; set; }
}
public abstract class AbstractRelationship<T>
{
public AbstractNode<T> Parent { get; set; }
public AbstractNode<T> Child { get; set; }
}
Is there a way to implement the "CreateNode" method in my library abstract below? Or can this only be done in client code outside the library? I current get the error "Cannot create an instance of the abstract class or interface 'ToplogyLibrary.AbstractNode"
public abstract class AbstractTopology<T>
{
// Properties
public Dictionary<T, AbstractNode<T>> Nodes { get; private set; }
public List<AbstractRelationship<T>> Relationships { get; private set; }
// Constructors
protected AbstractTopology()
{
Nodes = new Dictionary<T, AbstractNode<T>>();
}
// Methods
public AbstractNode<T> CreateNode()
{
var node = new AbstractNode<T>(); // ** Does not work **
Nodes.Add(node.Key, node);
}
}
}
public abstract class AbstractNode<T>
{
public T Key { get; set; }
}
public abstract class AbstractRelationship<T>
{
public AbstractNode<T> Parent { get; set; }
public AbstractNode<T> Child { get; set; }
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您无法创建抽象类的实例,这就是您收到错误的原因。
您可以做的是将 CreateNode 声明为抽象方法,并在任何后代类中实现它。
You cannot create an instance of an abstract class, which is why you are receiving the error.
What you could do instead is declare
CreateNode
as an abstract method, and implement it in any descendant classes.那么您想要创建什么具体的节点类?这也许应该留给具体的拓扑类吗?如果是这样,您可能希望使其抽象:
然后在具体拓扑类中提供具体实现。
或者,您也可以使您的类在节点类型中通用:
然后您可以像这样实现 CreateNode:
就我个人而言,我对涉及这么多抽象类的设计有点怀疑,但也许您有充分的理由。
Well what concrete node class do you want to be created? Is this perhaps something which should be left up to the concrete topology class? If so, you might want to make it abstract:
Then provide a concrete implementation in the concrete topology class.
Alternatively, you could make your class generic in the node type as well:
Then you could implement CreateNode like this:
Personally I get a little suspicious of designs involving this many abstract classes, but perhaps you've got good reasons.
定义一个受保护的纯抽象虚方法,CreateNode将调用该方法,子类返回一个新对象
CreateNodeImpl或其他东西。
define a protected pure abstract virtual method that CreateNode will call that the subclass return a new object
CreateNodeImpl or something.