Difference between CONST and READONLY in C #

xiaoxiao2021-03-17  202

The difference between const and readonly is always not clear, so I check the information.

The concept of Const is a variable that contains values ​​that cannot be modified. Constant expressions are expressible expressions that can be fully calculated at compile. Therefore, the constant cannot be initialized from the value extracted from one variable. If const Int a = b 1; b is a variable, it is obvious that the result is calculated when it is repeated, so constant is not to be initialized by variables. ReadOnly allows a field to constant, but can perform some operations, which can determine its initial value. Because readonly is executed when calculated, of course it can be initialized with certain variables. Readonly is an instance member, so different instances can have different constant values, which makes Readonly more flexible. The readonly keyword is different from the const keyword. 1. The Const field can only initialize in the declaration of this 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 compiled, while the Readonly field can be used to run the time. 3. Const default is static, and readonly must display a declaration if set to static. 4. Const For the constant of the reference type, the possible value can only be String and Null. Readonly can be any type * a question that needs to be aware of:

For a READONLY REFERENCE type, it is only defined to assign a value (write) operation. And read and write to its members is still unrestricted. Public static readonly class1 my = new class1 (); ... my.someproperty = 10; // Normal my = new class1 (); // error, the object is read-only, but if the Class1 in the above example is not a Class Is a struct, then the two statements behind will be wrong. Static Readonly: The Static in Java is performed once when a class is loaded. How is it executed in C #, I didn't find it. Very strange almost every Java book will say static problem, C # is often just how to use it, but should be initialized before the main function call, so Static Readonly is also runtime, you can use variables, such as: Private static Readonly string path = system.windows.Forms.Application.startuppath "AAA";

Author Blog:

http://blog.9cbs.net/kgdiwss/

转载请注明原文地址:https://www.9cbs.com/read-129597.html

New Post(0)