问题
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.
回答1:
class Example
{
int A = 5;
}
is equal to
class Example
{
int A;
public Example()
{
A = 5;
}
}
So the assignment is still part of a method (the constructor).
回答2:
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
回答3:
You are probably referring to field initializations:
class Foo
{
private static int i = 5;
}
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.
来源:https://stackoverflow.com/questions/3866055/statements-only-in-methods-but-what-about-declarations