当构件变量在类中初始化而不是在构造函数的帮助下初始化时,后台发生了什么?
谁能向我解释以下C#样本代码?
public class MyTestClass
{
private int x = 100;
private int y;
public MyTestClass
{
y = 200;
}
}
我了解到,当MytestClass实例化时,构造函数被调用,并为Y分配了200。但是在X的情况下会发生什么?什么时候实际分配给X?我应该想象这好像x在构造函数中一样,并在那里获得了最初的价值?
Could anyone explain me the following C# sample code?
public class MyTestClass
{
private int x = 100;
private int y;
public MyTestClass
{
y = 200;
}
}
I understand that when MyTestClass is instantiated, the constructor gets called and y is assigned the value 200. But what happens in case of x? When is 100 actually assigned to x? Should I imagine this as if x were in the constructor and got its initial value there?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
是的,在呈现的代码中,就像在构造函数中一样。参见编译器生成的IL代码:
Yes, in presented code it's like in a constructor. See IL code, generated by compiler:
在执行构造函数之前,请处理所有成员声明。这应该很明显,因为否则,在构造函数中不存在字段。如果在声明的位置初始化字段,则该分配会在加工成员时发生。这意味着,在您的情况下,
x
执行构造函数代码后已经具有值100。您可以将类似的初始化字段视为struct
字段的填充,而没有明确的构造函数。All member declarations are processed before the constructor is executed. That should be obvious because, otherwise, the fields wouldn't exist to be set in the constructor. If a field is initialised where it's declared, that assignment happens when the member is processed. That means that, in your case,
x
already has the value 100 when the constructor code is executed. You can think of initialised fields like that as being populated pretty much asstruct
fields are, which happens without an explicit constructor.