C# 抽象类,适用于数组初始化
众所周知,我们无法创建抽象类的实例。
我只是想知道,如果我们创建抽象类的数组,它一定会起作用。
例如,
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
初始化期间存储在数组中的值将全部为
null
,因此这实际上不会创建抽象类的任何实例。数组初始化对应于以下(正确)行:创建
AbstractClass[]
类型的数组实际上非常有用,因为您可以在数组中存储对某些具体(继承)类的引用。例如:然后您可以迭代
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: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:Then you can for example iterate over the
objects
array and callToString()
on all the objects.这里要记住的是,您没有创建任何
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 arenull
.只需初始化一个数组来保存 Creator 类的两个实例。它实际上并不为您实例化该类的任何实例。在初始化之前,这两个元素仍将为
null
。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.C# 中的数组与基本类型不同。
Creator
和Creator[]
是两种不同的类型。只有
Creator
是抽象的。Creator[]
不是抽象的,这就是为什么您可以创建它的实例。in C# arrays are different than the base type.
Creator
andCreator[]
are two different types.Only
Creator
is abstract.Creator[]
is not abstract that's why you can create instances of it.