“无法创建抽象类或接口的实例” C# 错误消息

发布于 2024-10-16 19:31:14 字数 228 浏览 2 评论 0原文

我将项目的基类更改为 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

对风讲故事 2024-10-23 19:31:14

您无法创建抽象类的实例。将其视为也可能包含一些实现逻辑的接口。如果您调用没有定义的抽象实例方法,您会期望发生什么?

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?

难得心□动 2024-10-23 19:31:14

我看到你之前的问题,其中你询问了“纯虚拟”(C# 中的abstract)的含义。

无法实例化抽象类的原因是它可能具有抽象成员,但没有实现。所以说你的类看起来像这样:

abstract class Airplane_Abstract
{
    public abstract int GetSomeInteger();
}

然后假设你可以实例化其中一个,你可以编写如下代码:

var airplane = new Airplane_Abstract();

// What would this be?
int integer = airplane.GetSomeInteger();

当然,我不相信你实际上拥有在抽象类中拥有抽象成员。但抽象类的一般思想是它不能单独存在;它不能独立存在。它必须在继承它的类中进一步定义。抽象成员最明显地说明了为什么会出现这种情况;可能还有其他原因。

例如,考虑一下形状。这是一个非常常见的例子,作为抽象类是有意义的。您不能真正实例化只是一个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 has abstract members, with no implementation. So say your class looks like this:

abstract class Airplane_Abstract
{
    public abstract int GetSomeInteger();
}

Then assuming you could instantiate one of these, you could write code like this:

var airplane = new Airplane_Abstract();

// What would this be?
int integer = airplane.GetSomeInteger();

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 a Shape, can you? ("Create a shape." "What kind of shape?" "No kind. Just an abstract shape." Doesn't really work, does it?)

忘东忘西忘不掉你 2024-10-23 19:31:14

您无法创建抽象类的实例。这就是抽象的意思。

You cannot create an instance of an abstract class. That's what abstract means.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文