Constant and field CLR learning lesson 7

Source: Internet
Author: User

1. Const: constant. When a field is compiled, the value is directly embedded intoProgramSet, that is, if you only rename the value of the constant in the set defined by the constant without re-compiling the entire program, then the constant in the set that previously referenced the constant is the original value, instead of re-compiled values (commonly known as version problems ).

2. fields: CLR supports type (static) fields, instance fields (non-static), and read/write fields;

Static field. The system dynamically allocates memory when this type is loaded into an application domain. It usually occurs when you reference thisType method is first compiled by JIT.

Instance field.When the instance is constructedDynamically allocate memory for it.

3. You only need to declare a field as a static read-only field to solve the const issue. Because every time this field is called static, the value of the Assembly where the static field is located must be re-referenced. If it is declared as readonly, it can only be read and cannot be written.

4. The instance read-only field can only be assigned a value within the constructor (the constructor is executed only once when the object is created for the first time; its value can be assigned multiple times );

The static read-only field can only be assigned values in the static constructor. The static constructor is executed when the type is referenced for the first time.

For example, public readonly string name = "why"; values can only be assigned to the following constructor:

Public class1 (string N)
{
//
// Todo: add the constructor logic here
//
This. Name = N;

};

Static readonly int Sn = 0; values can only be assigned to the following Constructor

Static class1 ()
{
Sn = 10;

}

It can only be assigned to the constructor. Otherwise, it cannot be compiled.

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.