ReadOnly allows you to set a field to a constant, but you can perform some operations to determine its initial value.
Because ReadOnly is performed at the time of calculation, it can be initialized with certain variables, of course.
ReadOnly are instance members, so different instances can have different constant values, which makes readonly more flexible.
The ReadOnly keyword differs from the const keyword.
1. The const field can be initialized only in the declaration of that 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.
2. The const field is a compile-time constant, and the ReadOnly field can be used to run the constant number.
3. The const default is static, and readonly must display the declaration if it is set to static.
4. Const for constants of reference types, the possible values can only be string and null.
ReadOnly can be of any type
* One of the issues to be noted is:
For a readonly Reference type, it is limited to the assignment (write) operation. The reading and writing of its members is still unrestricted.
The code is as follows |
Copy Code |
public static readonly Class1 i = new Class1 (); ... My. Someproperty = 10;//Normal my = new Class1 (); Error, the object is read-only |
However, if the Class1 in the example above is not a Class but a struct, then the following two statements will be faulted.
The code is as follows |
Copy Code |
Static ReadOnly: |
Static in Java is performed once when a class is loaded.
I didn't find out how to do it in C #. It is strange that almost every Java book will say Static, C # often only say how to use, but it should be initialized before the main function call, so the static readonly is also Run-time, you can use variables to pay the value, such as:
code is as follows |
copy code |
Private Static readonly String path = System.Windows.Forms.Application.StartupPath + "AAA"; |