当前位置: 动力学知识库 > 问答 > 编程问答 >

c# - How does, Defining and Instantiating variables in class scope, interpretted internally

问题描述:

Class1 declares a variable and instantiates it. defining and instantiating statement is allowed to be class scope.

class class1

{

public bool variable = false;

}

With the same logic why cannot Class2 instantiate the variable. why instantiating statement is not allowed to be in class scope like this.

class class2 : class1

{

variable = false;

}

I am interested, if there is any logical explanation behind this. May be the Compiler interprets such defining in some special way.

网友答案:

Other than inline initialization, statements are not allowed in the class body without being contained in something like a constructor, method, or property.

If you want to initialize the variable to something else, stick it in the constructor (this is what the constructor is for):

public class Class2 : Class1
{
    public Class2()
    {
        variable = false;
    }
}

Another similar question:

Statements only in methods, but what about declarations?

In summary, declaration is only allowed at class scope. Inline initialization is equivalent to initializing the member variables in the constructor - my guess is this was added as syntactic sugar, as inline initialization is stock-and-trade for lots of languages.

Also a quick note on the naming, classes are usually Title Cased.

网友答案:

Never saw a problem with your second case, except the fact that in second case you didn't define a TYPE of the variable.

EDIT

I think I missuderstood your question:

The member variable is a part of the base class definiton. You can not access a public member of a class out of any method. That is it.

分享给朋友:
您可能感兴趣的文章:
随机阅读: