Readonly vs. const [C #]
Updated on Friday, October 29, 2004
Writen by Allen Lee
Features:
READONLY and CONST are used to identify constants [1]. Const can be used to modify the Field or a local variable (Local variable); and readonly is only used to modify the Field of the Class. The value of the constant constant must be clear and constant when compiling; the readonly constant is different, that is, its value can be compiled at runtime, of course, it must also follow the constraint as a constant, that is, the value must be constant. change. The constant constant must be assigned to the declaration, and ensure that the value can be determined and constant at compile; and the readOrthly constant can determine and constantly determine and constantly determine and constantly confer the compilation according to the situation, or will The initialization of its value is completed by the instant constructor. Such as: public retadonly string m_now = datetime.now.tostring ();, M_NOW will vary with the actual situation at runtime. Const constant belongs to the class level instead of instance object level (I cannot use Static Object Level), and the value of this constant will be shared by all instance objects of the entire class (detailed discussion see the Remark area behind) ). Readonly constants can either the class level or an instance object level, depending on how its declaration and initialization work implementation. Readonly can be used in conjunction with Static, which is used to specify the constant level level, and complete the initialization work is complete (static constructor) (relevant to how to declare the Readonly constant as a class level or instance object level, see later REMARK area). The type that can be declared as constant as a constant must be the following primitive type: Sbyte, Byte, Short, Ushort, Int, Uint, Long, Ulong, CHAR, FLOAT, DOUBLE, FLOAT, BOOL, DECIMAL, STRING . Object, array (array) and structure cannot be declared as a constant. Under normal circumstances, the reference type cannot be declared as constant constant, but there is an exception: String. The value of this reference type Const can have two cases, String or NULL. In fact, String is a reference type, but .NET is specially processed, this processing is called a string constant (immutable), so that the value of String has read only features. For content string constant content, you can refer to "Microsoft .NET Framework Design (Revised)".
EXAMPLES:
Using system; public class order {public order () {guid = guid.newguid (); id = guid.tostring ("d");} // For each order, its order serial number is constant determined in real time. . Public Readonly string ID; public override string toString () {return "Order ID:" id;}} EXPLAINTION:
If combined with databases, ID Field usually associates the primary key to a table, such as OrderID of the OrderS table. The database of the database is usually used in the following three ways:
Automatic deliver value. You can activate automatic incremental characteristics by setting Datacolumn.AutoInCrement to TRUE values. The only name. This is a unique serial number using the algorithm that uses your own definition. GUID (globally unique identifier). You can generate a GUID via the System.GUID structure, such as the above.
Using
System; Class
Customer
{Public Customer (string name, int kind) {m_Name = name; m_Kind = kind;} public const int NORMAL = 0; public const int VIP = 1; public const int SUPER_VIP = 2; private string m_Name; public string Name {get {return m_Name;}} private readonly int m_Kind; public int Kind {get {return m_Kind;}} public override string ToString () {if (m_Kind == SUPER_VIP) return "Name:" m_Name "[SuperVip]"; Else if (m_kind == vip) return "name:" m_name "[vip]"; else return "name:" m_name "[normal]";}}
REMARKS:
Under normal circumstances, if you need a constant constant, it is generally recognized and used as a single use, such as a circularity, gold segmentation ratio, and the like. You can consider using Const constants, such as public const Double pi = 3.1415926 ;. If you need to declare constant, this constant will decide with the actual operation, then readonly constants will be a good choice, such as the order number ORDER.ID of the first example above. Also, if you want to indicate the default value inside the object, this type of value is usually constant, then Const can be considered. For more time we reconstruct the source code (using Replace Magic Number With Symbolic Constant), it is necessary to remove this feature of Magic Number. What is the problem of the class-level or instance-level or instance object level, let's take a look at the following code: USING DIRECTIVES
#region using directivesusing system; usng system.text; #endregion
Namespace
ConstantLab
{Class Program {static void main (string [] args) {constant c = new constant (3); console.writeline ("constint =" constant.constint.writeLine ("readonlyint =" c.ReadonlyInt.ToString ()); Console.WriteLine ( "InstantReadonlyInt =" c.InstantReadonlyInt.ToString ()); Console.WriteLine ( "StaticReadonlyInt =" Constant.StaticReadonlyInt.ToString ()); Console.WriteLine ( " Press any key to continue "); Console.ReadLine ();}} class Constant {public Constant (int instantReadonlyInt) {InstantReadonlyInt = instantReadonlyInt;} public const int ConstInt = 0; public readonly int ReadonlyInt = 1; public readonly int InstantReadonlyInt; Public static readonly int staticreadOnlyint = 4;}}
When using the Visual C # In Main () Insert Constant's related field, find ReadonlyInt and InstantReadOnlyInt need to specify the instance object of Constant; Constint and StaticReadOnlyint have to specify the constant class (see above). It can be seen that the constant modified with const or static readonly is a class level; the readOnly is modified, whether it is directly initialized or initialized or in an instance constructor, belongs to an instance object level. Under normal circumstances, if you need to express a set of related compiles to determine constants, you can consider using enumeration types (enum) instead of embedding multiple constants directly into the Class as Field, but these two ways are not absolute优 孰 孰 分 分. Using
System; ENUM
Customerkind
{Supervip, VIP, NORMAL}
Class
Customer
{Public Customer (string name, CustomerKind kind) {m_Name = name; m_Kind = kind;} private string m_Name; public string Name {get {return m_Name;}} private CustomerKind m_Kind; public CustomerKind Kind {get {return m_Kind;}} Public override string toString () {return "name:" m_name "[" m_kind.tostring () "]";}}
However, when such a code that uses enumeration and conditions, the code that is judged to hinder your more flexible extension, and it is possible to increase the increase in maintenance costs, you can make a polymorphism, use the Replace Conditional With Polymorphism to make the code Refactoring. (For more details on polymorphism, see "Do you have a multi-state today?"
Comments:
Readonly Field accurately, it should be translated into a "read-only domain". Here is to uniform translation terms to "constants" modified with Const, and hope that there is no misunderstanding.