Convert to C # Read-Only Field

Source: Internet
Author: User

The read-only field can be assigned a value to the read-only field in the constructor, but cannot be assigned elsewhere. The read-only field can also be an instance field rather than a static field, each instance of the class can have different values. Unlike the const field, if you want to set the field to static, it must be explicitly declared.

 

If you have an MDI program for editing a document, you must limit the number of documents that can be opened at the same time. Now assume that you want to sell different versions of the software, and customers can upgrade their versions to open more documents at the same time. Obviously, you cannot hard program the maximum number of documents in the source code. Instead, a field is required to indicate the maximum number of documents. This field must be read-only-read from the registry or other file storage each time the program is installed. The Code is as follows:

Public class extends enteditor

{

Public static readonly uint maxcompute ENTs;

 

Static plugin enteditor ()

{

MaxDocuments = DoSomethingToFindOutMaxNumber ();

}

}

In this example, the field is static, because every time you run the program instance, you only need to store the maximum number of documents once. This is why static constructor initializes it. If the read-only field is an instance field, initialize it in the instance constructor.

Public class Document

{

Public readonly DateTime CreationDate;

Public Document ()

{

CreationDate = someDate;

}

}

 

Note that you do not need to assign a value to a read-only field in the constructor. If no value is assigned, its value is the default value of its data type or the value initialized to it during declaration. This applies to static and instance read-only fields.

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.