C # variable initialization problem: the initial value of a field cannot reference non-static fields, methods, or attributes,

Source: Internet
Author: User

C # variable initialization problem: the initial value of a field cannot reference non-static fields, methods, or attributes,

Http://www.cnblogs.com/bluestorm/p/3432190.html

Problem: non-static fields, methods, or attributes cannot be referenced in the field's Initial Value Setting item

The reason for the following code error is that the fields defined in the class cannot be used. Why?
Public class Test
{
Public Test ()
{
}
Public int Age = 23;
Public int temp = Age; // the initial value of the ERROR field cannot reference non-static fields, methods, or attributes.
}

 

C # specifies that only attributes or variables can be defined within the class and initialized. Variables cannot be referenced directly.

The field is called before the class instance is initialized.

The initialization of fields in c # is prior to the constructor.

String y = "asdf" + x; it is actually y = "asdf" + this. x;

Because this is not initialized yet, an error is reported during compilation.

The allocation time of attribute memory and variable memory is different.
The attribute is allocated when it is used, and the variable is allocated during class initialization.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.