Statements only in methods, but what about declarations?

梦想的初衷 提交于 2019-12-13 16:50:27

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!