“无法创建抽象类或接口的实例” C# 错误消息
我将项目的基类更改为 abstract
,现在收到以下错误:
无法创建抽象类或接口的实例
我收到错误是因为不允许命名 abstract
类的新实例吗?
newPlane = new Airplane_Abstract(name, position);
I changed my base class to abstract
for a project and now I'm receiving the following error:
Cannot create an instance of the abstract class or interface
Am I receiving the error because naming a new instance of an abstract
class is not allowed?
newPlane = new Airplane_Abstract(name, position);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您无法创建抽象类的实例。将其视为也可能包含一些实现逻辑的接口。如果您调用没有定义的抽象实例方法,您会期望发生什么?
You can't create an instance of an abstract class. Think of it as an interface that may contain some implementation logic as well. What would you expect to happen if you called an abstract instance method with no definition?
我看到你之前的问题,其中你询问了“纯虚拟”(C# 中的
abstract
)的含义。无法实例化抽象类的原因是它可能具有抽象成员,但没有实现。所以说你的类看起来像这样:
然后假设你可以实例化其中一个,你可以编写如下代码:
当然,我不相信你实际上拥有在抽象类中拥有抽象成员。但抽象类的一般思想是它不能单独存在;它不能独立存在。它必须在继承它的类中进一步定义。抽象成员最明显地说明了为什么会出现这种情况;可能还有其他原因。
例如,考虑一下
形状
。这是一个非常常见的例子,作为抽象类是有意义的。您不能真正实例化只是一个Shape
,对吗? (“创建一个形状。”“什么样的形状?”“没有种类。只是一个抽象的形状。”实际上不起作用,不是吗?)I saw your earlier question, in which you asked about the meaning of "pure virtual" (
abstract
in C#).The reason you cannot instantiate an
abstract
class is that it presumably hasabstract
members, with no implementation. So say your class looks like this:Then assuming you could instantiate one of these, you could write code like this:
Granted, I don't believe you actually have to have abstract members in an abstract class. But the general idea of an abstract class is that it's one that cannot exist on its own; it must be further defined in a class which inherits from it. Abstract members are the most obvious illustration of why this would be; there could be other reasons.
Think of
Shape
, for example. This is a pretty common example of something that would make sense as an abstract class. You can't really instantiate just aShape
, can you? ("Create a shape." "What kind of shape?" "No kind. Just an abstract shape." Doesn't really work, does it?)您无法创建抽象类的实例。这就是抽象的意思。
You cannot create an instance of an abstract class. That's what abstract means.