类型静态构造函数调用
可能的重复:
为什么 CLR 不总是调用值类型构造函数
在 Richter 的书中找到下一个代码(我对其进行了一些简化):
internal struct SomeValType
{
static SomeValType()
{
Console.WriteLine("This never gets displayed");
}
public Int32 X;
}
public sealed class Program
{
public static void Main()
{
SomeValType a = new SomeValType { X = 123 };
Console.WriteLine(a.X);
}
}
输出:
123
无法理解为什么静态构造函数 nevel 调用中的 WriteLine
。查看 ILDasm - 存在构造函数代码和方法调用。如果我向 SomeValType
添加任何静态变量并在构造函数中初始化它,则 WriteLine
可以正确调用。
有人可以解释一下这种情况下的行为吗?谢谢。
Possible Duplicate:
Why doesn't the CLR always call value type constructors
Found next code in Richter's book (I have simplified it a little bit):
internal struct SomeValType
{
static SomeValType()
{
Console.WriteLine("This never gets displayed");
}
public Int32 X;
}
public sealed class Program
{
public static void Main()
{
SomeValType a = new SomeValType { X = 123 };
Console.WriteLine(a.X);
}
}
Output:
123
Can't understand why WriteLine
in static constructor nevel calls. Looked at ILDasm - constructor code and calling of method are present. If I add any static variable to SomeValType
and init it in constructor then WriteLine
calling correctly.
Can someone explain, please, behavior in such situation? Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
可能是因为您从未访问真实构造函数或静态字段。
值类型的默认构造函数很特殊。这只是对所有字段的默认值进行二进制初始化(即整个结构的二进制零)
Probably because you're never accessing a real constructor nor a static field.
The default constructor of value types is special. It's just an initialization to binary the default value of all fields(i.e. binary zero the whole struct)
来自MSDN:
自动初始化类 [强调我的]
在创建第一个实例之前
或引用任何静态成员。
看来“类”这个词是这里的关键。将 SomeValType 设为类会导致在创建该类型的第一个实例时调用静态构造函数,如上所述。然而,当它是一个结构时,似乎您需要访问静态字段或调用静态方法才能触发此行为。这是一个错误还是有意为之?
From MSDN:
automatically to initialize the class [emphasis mine]
before the first instance is created
or any static members are referenced.
It seems that the word class is the key here. Making SomeValType a class results in a static constructor invocation upon creating the first instance of the type as stated above. When it is a struct, however, it seems you need to access a static field or call a static method for this behavior to be triggered. Is this a bug or is it intended?