在 CLR Via C# 4th Edition 的 pg 185/186 上,它有这样的代码示例:
class Program
{
static void Main(string[] args)
{
Rectangle r = new Rectangle();
}
}
internal struct Point
{
public Int32 m_x, m_y;
public Point()
{
m_x = m_y = 5;
}
}
internal sealed class Rectangle
{
public Point m_topLeft, m_bottomRight;
public Rectangle()
{
}
}
这不会编译,因为您不能为结构定义无参数构造函数。
杰夫接着说:
C# purposely disallows value types from defining parameterless constructors to remove any confusion a developer might have about when that constructor gets called.
但是,如果将 struct
替换为 class
,代码会编译,并且在运行时,不会调用 Point
构造函数,这对于刚接触编程的人来说可能出乎意料。
编辑:也许我理解有误,但我认为 Jeff 是想说一些人可能认为如果值类型有一个无参数的构造函数,它会为每个Point array = new Point[100];
中的实例,这是不会发生的。如果是这样,那么您对引用类型也有同样的潜在混淆,对吧?
我知道 Jon Skeet 写了一个答案 here ,但是所有这些点也可以应用于引用类型,但引用类型是允许无参数构造函数。
最佳答案
事实上,Jon 的论点不能应用于引用类型这一事实只会加强他的观点。
如果在初始化引用类型数组时从未调用引用类型的构造函数(因为没有实例化任何内容),那么只有保持行为一致并且不调用任何构造函数才有意义当您初始化值类型数组时。
关于c# - 为什么类可以有明确的无参数构造函数而结构不能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25015208/