C# const常量詳細介紹
C#語言有很多值得學習的地方,這里我們主要介紹C# const常量,包括介紹readonly和const所修飾的變量等方面。
一般情況下,如果你需要聲明的常量是普遍公認的并作為單個使用,例如圓周率,黃金分割比例等。你可以考慮使用C# const常量,如:public const double PI = 3.1415926;。如果你需要聲明常量,不過這個常量會隨著實際的運行情況而決定,那么,readonly常量將會是一個不錯的選擇,例如上面***個例子的訂單號Order.ID。
另外,如果要表示對象內部的默認值的話,而這類值通常是常量性質的,那么也可以考慮const。更多時候我們對源代碼進行重構時(使用Replace Magic Number with Symbolic Constant),要去除魔數(Magic Number)的影響都會借助于const的這種特性。
對于readonly和const所修飾的變量究竟是屬于類級別的還是實例對象級別的問題,我們先看看如下代碼:
- using System;
- namespace ConstantLab
- {
- class Program
- {
- static void Main(string[] args)
- {
- Constant c = new Constant(3);
- Console.WriteLine("ConstInt = " + Constant.ConstInt.ToString());
- Console.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;
- }
- }
使用Visual C#在 Main()里面使用IntelliSence插入Constant的相關field的時候,發現ReadonlyInt和 InstantReadonlyInt需要指定Constant的實例對象;而ConstInt和StaticReadonlyInt卻要指定 Constant class(參見上面代碼)。可見,用const或者static readonly修飾的常量是屬于類級別的;而readonly修飾的,無論是直接通過賦值來初始化或者在實例構造函數里初始化,都屬于實例對象級別。
一般情況下,如果你需要表達一組相關的編譯時確定常量,你可以考慮使用枚舉類型(enum),而不是把多個C# const常量直接嵌入到class中作為field,不過這兩種方式沒有絕對的孰優孰劣之分。
- 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() + "]";
- }
- }
【編輯推薦】