On pg 185/186 of CLR Via C# 4th Edition, it has this code example:
通过c# 4版CLR的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()
{
}
}
This won't compile because you can't define a parameterless constructor for a struct.
这不会编译,因为您不能为结构体定义一个无参数的构造函数。
Jeff goes on to say:
杰夫接着说:
C# purposely disallows value types from defining parameterless constructors to remove any confusion a developer might have about when that constructor gets called.
c#故意不允许值类型定义参数化的构造函数,以消除开发人员在调用该构造函数时可能遇到的任何混乱。
However if you replace struct
with class
, the code compiles, and when run, the Point
constructor doesn't get called, which could be unexpected for people new to programming.
但是,如果用类替换struct,代码就会编译,运行时不会调用点构造函数,这对于编程新手来说可能是意想不到的。
EDIT: Maybe I've understood it incorrectly, but I think Jeff is trying to say that some people may think that if value types were to have a parameterless constructor, it would be called for every instance in Point array = new Point[100];
, which is not what would happen. If so, then you've got the same potential confusion with reference types right?
编辑:也许我理解错了,但是我认为Jeff在试图说明,如果值类型有一个无参数的构造函数,那么它会在Point array = new Point[100]中为每一个实例调用,这不是会发生的事情。如果是这样,那么你就会和引用类型有同样的潜在混淆,对吧?
I know Jon Skeet wrote an answer here, however all those points could also be applied to reference types, yet reference types ARE allowed parameterless constructors.
我知道Jon Skeet在这里写了一个答案,但是所有这些点也可以应用到引用类型,但是引用类型是允许的无参数构造函数。
1 个解决方案
#1
0
In fact, the fact that Jon's arguments can't be applied to reference types only strengthens his points.
事实上,Jon的论点不能用于引用类型这一事实只会加强他的观点。
If a reference type's constructor is never called when you initialize an array of reference types (because there's nothing being instantiated), then it would only make sense to keep the behaviour consistent and not call any constructor when you initialize an array of value types.
如果引用类型的构造函数在初始化引用类型数组时从未被调用(因为没有实例化),那么只有在初始化值类型数组时保持行为一致,并且不调用任何构造函数才有意义。
#1
0
In fact, the fact that Jon's arguments can't be applied to reference types only strengthens his points.
事实上,Jon的论点不能用于引用类型这一事实只会加强他的观点。
If a reference type's constructor is never called when you initialize an array of reference types (because there's nothing being instantiated), then it would only make sense to keep the behaviour consistent and not call any constructor when you initialize an array of value types.
如果引用类型的构造函数在初始化引用类型数组时从未被调用(因为没有实例化),那么只有在初始化值类型数组时保持行为一致,并且不调用任何构造函数才有意义。