Read-only fields
When a field declaration contains readonly a modifier, the field that is introduced by the declaration is read-only. A direct assignment to a read-only field can occur only as part of a declaration, or in an instance constructor or a static constructor in the same class. (In these contexts, a read-only field can be assigned multiple times.) Accurately, the readonly field is allowed to be directly assigned only in the following contexts:
- In the variable declarator that is used to introduce the field (by adding a variable initializer).
- For instance fields, in the instance constructor of the class that contains the field declaration, and for the static field, in the static constructor of the class that contains the field declaration. It is also only in these contexts that the
readonly field as out or ref parameter is passed to be valid.
In any other context, attempting to assign a readonly value to a field or pass it as a out or parameter will result in ref a compile-time error.
C # constant data and read-only fields
Constant data
C # provides a const keyword to define constants, which is useful if we want to define a set of known values logically related to a class or struct for an application.
If we create a Mymathclass tool class and need to define a PI value (if it is 3.14), if you do not want other developers to change the PI value, you can use the following constants to define the PI value:
1 classMymathclass2 {3 //defined as constant data4 Public Const DoublePi=3.14;5 }6 class Program7 {8 Public Static voidMain (string[] args)9 {Ten //Note: Because constant data is implicitly static, it can only be called directly at the class level (MYMATHCLASS.PI). OneConsole.WriteLine ("the PI value is: {0}", Mymathclass.pi); A - //Error! Constant data cannot be modified. -Mymathclass.pi=3.15; the console.readline (); - } -}
Note: When defining constants, you must specify the initial values for constants, and constants cannot be modified once they are defined.
1 classMymathclass2 {3 //try to assign a value to a constant in the constructor4 Public Const DoublePI;5 PublicMymathclass ()6 {7 //Error! 8Pi=3.14;9 } Ten}
You must know the value of the constant at compile time!
Read-only fields
The concept of close contact with constants is a read-only field (not to be confused with read-only properties, read-only properties refer to properties with only get blocks). Similar to constants, read-only fields cannot be changed after assignment. However, unlike constants, assigning to read-only fields can be determined at run time. So assigning a value to a read-only field at the scope of the constructor is legal (not anywhere else!). )。
1 classMymathclass2 {3 //You can assign a value to a read-only field in the constructor, not anywhere else!4 Public ReadOnly DoublePI;5 PublicMymathclass ()6 {7Pi=3.14;8 } 9 Public voidChangepi ()Ten { One //Error! APi=3.14; - } -}
Another: Read-only fields are not implicitly static, and you need to use the static keyword to define a static read-only field.
Question: Please describe the difference between const and readonly.
The const keyword is used to modify the declaration of a field or local variable. It specifies that the value of a field or local variable cannot be modified. A constant declaration introduces one or more constants of a given type, happy oh. The declaration of a const data member must contain an initial value, and the initial value must be a constant expression. Because it is at compile time it needs to be fully evaluated. A const member can be initialized with another const member, provided there is no cyclic dependency between the two. The readonly evaluation assignment at run time allows us to defer the initialization of object to run time while ensuring "read-only access".
The ReadOnly keyword differs from the CONST keyword: the const field can only be initialized in the declaration of the field. The readonly field can be initialized in a declaration or constructor. Therefore, depending on the constructor used, the ReadOnly field may have different values. In addition, the Const field is a compile-time constant, and the ReadOnly field can be used to run a constant number. ReadOnly can only be initialized at the time of declaration or in the constructor.
An issue to be noted for enumeration and constants
Enumerations in. NET are actually numeric constants, similar to Const. When we use the value or constant represented by the enumeration in our code, the compiler actually writes the value directly and does not read the value at run time. Here is an example:
We want to set up a class library project, called ClassLibrary1, and then build a console project, named ConsoleApplication2, with the following structure:
The code in CLASS1 in the ClassLibrary1 project is:
1 usingSystem;2 usingSystem.Collections.Generic;3 usingSystem.Linq;4 usingSystem.Text;5 6 namespaceClassLibrary17 {8 Public classMyClass9 {Ten Public Static stringSTR1 ="str1"; One Public Const stringSTR2 ="str2"; A } - - Public enumMyEnum the { -one =1, -both =2, -three =3 + } -}
Defines an enumeration and a static field, a constant field.
ConsoleApplication2 project refers to project A, the code is as follows:
1 usingSystem;2 usingClassLibrary1;3 4 class Program5 {6 Public Static voidMain (string[] args)7 {8Console.WriteLine ((int) myenum.one);9 Console.WriteLine (MyEnum.One.ToString ());Ten One Console.WriteLine (MYCLASS.STR1); A Console.WriteLine (MYCLASS.STR2); - - Console.readkey (); the } -}
Let's look at how the program class is recompiled with the reflector tool:
Public classmyclass{// Fields Public Static stringstr1; Public Const stringSTR2 ="str2"; //Methods StaticMyClass (); PublicMyClass ();} Note: Two constructors are added here automatically, one static and one non-static.
1 Public Static voidMain (string[] args)2 {3Console.WriteLine (1);4 Console.WriteLine (MyEnum.One.ToString ());5 Console.WriteLine (MYCLASS.STR1);6Console.WriteLine ("str2");7 Console.readkey ();8 }
The compiler writes the value of the Myenum.one (int) to the constant field str2 directly into the code, rather than reading it at run time.
The consequence of this is that if you modify the order of the enumerations in the a project or enumerate the corresponding values (or change the value of the constant field str2), such as the value of Myenum.one 2, and do not recompile the test project, the result will not change.
Programming C #. Classes and Objects. Read-only fields