There is a way in programming languages to tell the compiler that a piece of data is constant. There are two requirements
1. A compiler constant that never changes
2. A value that is initialized at runtime, and this value will not be changed
In Java , use final modifier variables to achieve these two requirements
<pre name="code">//Compiler constant private final int valueOne = 9;private static final int VALUE_TWO = 99;public static final int VALUE_THREE = 39;//The value initialized at runtime, and the value will not be changed private final int i4 = rand.nextInt(20);static final int INT_5 = rand.nextInt(20);</span>
When final modifys the basic data type, keep the data constant and unchanged
When final modify object reference, the reference is kept constant. Once the reference is initialized to point to an object, it cannot be changed to point to another object.
However, the object itself can be modified
Final modify parameters in the method parameter list, meaning that the object pointed to by the parameter reference cannot be changed in the method. This feature is mainly used to pass data to anonymous internal classes.
Also, in Java
The purpose of final modification method is to explicitly prohibit subclasses from overwriting this method
Final modification class, inheritance is prohibited
How do you implement these two requirements in C#?
Requirement 1: Compiler Constants
Const modifies constants, which must be used for calculations at compile time. Constants are always static but do not have to (actually, not allowed) include modifier static in constant declaration
Requirement 2: Runtime constants
The readonly keyword may sometimes require some variables whose value should not be changed, but its value is unknown before running.
C# provides another type of variable for this situation: read-only fields
Also, in C#
The sealed modification method is to explicitly prohibit subclasses from overwriting this method.
sealed modification class, inheritance is prohibited
The above is the brief discussion of the final keyword in Java and the const and readonly keywords in C#. I hope everyone can support Wulin.com~