语句只能在方法中使用,但是声明呢?
在 MSDN 上我发现:
在 C# 中,每个执行的指令都是在方法的上下文中完成的。
但我还了解到,int A=5;
语句可以位于类主体中。看起来它不在方法体中,那么为什么这是可能的呢?这可能只是术语混淆,但我想知道。
On MSDN I found:
In C#, every executed instruction is done so in the context of a method.
But I also read that an int A=5;
statement can be in the class body. It seems it's not in a method body, so why this is possible? It is probably just term confusion but I would like to know.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
阿德里安是对的。进一步澄清:“int A = 5;”仅当它位于方法体内时才是一条语句。当它位于方法体外部时,它是带有初始值设定项的字段声明,逻辑上将其移动到构造函数体中。
初始化器如何工作的确切语义有点棘手。有关于此的一些想法,请参阅:
http://blogs.msdn.com/b/ericlippert/archive/2008/02/15/why-do-initializers-run-in-the -opposite-order-as-constructors-part-one.aspx
http://blogs.msdn.com/b/ericlippert/archive/2008/02/18/why -do-initializers-run-in-the-opposite-order-as-constructors-part-two.aspx
Adrian is correct. To clarify further: "int A = 5;" is only a statement when it is inside a method body. When it is outside a method body then it is a field declaration with an initializer, which is logically moved into the constructor body.
The exact semantics of how the initializers work is a bit tricky. For some thoughts on that, see:
http://blogs.msdn.com/b/ericlippert/archive/2008/02/15/why-do-initializers-run-in-the-opposite-order-as-constructors-part-one.aspx
http://blogs.msdn.com/b/ericlippert/archive/2008/02/18/why-do-initializers-run-in-the-opposite-order-as-constructors-part-two.aspx
等于
所以赋值仍然是方法(构造函数)的一部分。
is equal to
So the assignment is still part of a method (the constructor).
您可能指的是字段初始化:
即使这条指令也在方法的上下文中运行。在这种特殊情况下,它是静态构造函数。如果该字段不是静态的,那么它将是普通的构造函数。
You are probably referring to field initializations:
Even this instruction runs inside the context of a method. In this particular case it is the static constructor. If the field is not static then it will be the normal constructor.