C# - 修飾詞-Part2

繼上一篇C# 修飾詞-Part1,這次要介紹的是兩個用法較相近的 const 與 readonly:


const

const只能加在欄位與區域變數之前,加上const的變數代表為常數,其值不能被修改,const資料只能塞數值或字元字串類型的資料型別,因為const是在編譯時期產生,所以能夠變動的彈性不高,也因為如此const在宣告時就必須給定初始化值,另外,const前不能使用static,只要宣告成public 就能夠當作靜態使用

readonly

readonlyconst功能類似,但readonly只能加在欄位,使用彈性較const高,因為readonly是在執行時期產生,且可以在宣告與constructor中初始化,以下表格為constreadonly比較表:


const
readonly
使用位置
Field, Local Variable
Field
產生時期
Compile
Execution
效能
較高
較差
初始化位置
宣告區域
宣告區域, Constructor
static
不可加
可加
資料型別
數值, 字元, 字串
皆可
引用模式
引用值
引用變數

在余小章的部落格中,有談到在大型專案中,如果專案採用引用類別庫的方式使用類別庫中宣告的const與readonly,在專案需變動const與readonly值時,如果只將類別庫重新編譯覆蓋掉專案的DLL,會造成const值為舊值的情況,需要將整個專案重新編譯

範例程式:
using System;

namespace Test
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine(Test.X);
            Console.WriteLine(Test.Y);

            Console.ReadKey();
        }
    }

    public class Test
    {
        public const int X = 100;
        public static readonly int Y = 0;

        static Test()
        {
            Y = 12;
        }
    }
}

輸出:






參考來源:

留言