C# const常量詳細(xì)介紹
C#語(yǔ)言有很多值得學(xué)習(xí)的地方,這里我們主要介紹C# const常量,包括介紹readonly和const所修飾的變量等方面。
一般情況下,如果你需要聲明的常量是普遍公認(rèn)的并作為單個(gè)使用,例如圓周率,黃金分割比例等。你可以考慮使用C# const常量,如:public const double PI = 3.1415926;。如果你需要聲明常量,不過(guò)這個(gè)常量會(huì)隨著實(shí)際的運(yùn)行情況而決定,那么,readonly常量將會(huì)是一個(gè)不錯(cuò)的選擇,例如上面***個(gè)例子的訂單號(hào)Order.ID。
另外,如果要表示對(duì)象內(nèi)部的默認(rèn)值的話,而這類值通常是常量性質(zhì)的,那么也可以考慮const。更多時(shí)候我們對(duì)源代碼進(jìn)行重構(gòu)時(shí)(使用Replace Magic Number with Symbolic Constant),要去除魔數(shù)(Magic Number)的影響都會(huì)借助于const的這種特性。
對(duì)于readonly和const所修飾的變量究竟是屬于類級(jí)別的還是實(shí)例對(duì)象級(jí)別的問(wèn)題,我們先看看如下代碼:
- 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的相關(guān)field的時(shí)候,發(fā)現(xiàn)ReadonlyInt和 InstantReadonlyInt需要指定Constant的實(shí)例對(duì)象;而ConstInt和StaticReadonlyInt卻要指定 Constant class(參見上面代碼)??梢?,用const或者static readonly修飾的常量是屬于類級(jí)別的;而readonly修飾的,無(wú)論是直接通過(guò)賦值來(lái)初始化或者在實(shí)例構(gòu)造函數(shù)里初始化,都屬于實(shí)例對(duì)象級(jí)別。
一般情況下,如果你需要表達(dá)一組相關(guān)的編譯時(shí)確定常量,你可以考慮使用枚舉類型(enum),而不是把多個(gè)C# const常量直接嵌入到class中作為field,不過(guò)這兩種方式?jīng)]有絕對(duì)的孰優(yōu)孰劣之分。
- 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() + "]";
- }
- }
【編輯推薦】