C# 抽象类,适用于数组初始化

发布于 2024-09-29 06:51:50 字数 408 浏览 2 评论 0原文

众所周知,我们无法创建抽象类的实例。

我只是想知道,如果我们创建抽象类的数组,它一定会起作用。

例如,

public abstract class Creator
{
    public abstract void DoSomething();
}

Creator creator = new Creator(); // this will give you compilation error!

Creator[] creator = new Creator[2]; // this will SURE work and will NOT give you compilation error.

有人可以告诉我为什么会发生这种情况以及为什么它与数组初始化一起工作吗?

提前致谢。

As we know that we CANNOT create the instance of abstract class.

I just want to know that if we create the array of abstract class, it will sure work.

E.g.

public abstract class Creator
{
    public abstract void DoSomething();
}

Creator creator = new Creator(); // this will give you compilation error!

Creator[] creator = new Creator[2]; // this will SURE work and will NOT give you compilation error.

Can anybody please let me know that why this is happening and why it is working with array initialization?

Thanks in advance.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(4

套路撩心 2024-10-06 06:51:50

初始化期间存储在数组中的值将全部为 null,因此这实际上不会创建抽象类的任何实例。数组初始化对应于以下(正确)行:

Creator creator = null;

创建 AbstractClass[] 类型的数组实际上非常有用,因为您可以在数组中存储对某些具体(继承)类的引用。例如:

var objects = new object[2];
objects[0] = "Hello";
objects[1] = new System.Random();

然后您可以迭代 objects 数组并对所有对象调用 ToString()

The values stored in the array during the initialization will all be null, so this doesn't actually create any instance of the abstract class. Array initialization corresponds to the following (correct) line:

Creator creator = null;

Creating arrays of a type AbstractClass[] is actually quite useful, because you can then store references to some concrete (inherited) class in the array. For example:

var objects = new object[2];
objects[0] = "Hello";
objects[1] = new System.Random();

Then you can for example iterate over the objects array and call ToString() on all the objects.

可爱暴击 2024-10-06 06:51:50

这里要记住的是,您没有创建任何 Creator 实例,您正在创建这些类型的数组,其值为 null

The thing to remember here, is you're not creating any instances of Creator, you're creating an array of those types, who's value's are null.

知你几分 2024-10-06 06:51:50
Creator[] creator = new Creator[2];

只需初始化一个数组来保存 Creator 类的两个实例。它实际上并不为您实例化该类的任何实例。在初始化之前,这两个元素仍将为 null

Creator[] creator = new Creator[2];

simply initializes an Array to hold two instances of the Creator class. It doesn't actually instantiate any instances of the class for you. Both of those elements will still be null until you initialize them.

美胚控场 2024-10-06 06:51:50

C# 中的数组与基本类型不同。
CreatorCreator[] 是两种不同的类型。
只有Creator是抽象的。 Creator[] 不是抽象的,这就是为什么您可以创建它的实例。

in C# arrays are different than the base type.
Creator and Creator[] are two different types.
Only Creator is abstract. Creator[] is not abstract that's why you can create instances of it.

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