Try   HackMD

[C#] const vs readonly

tags: C# Programming

const

  • 編譯時期常數
  • 只能用於primitive type或refernce type
  • 只能在宣告時賦值
  • 在class內,被視為靜態成員(static member)

readonly

  • 執行時期常數
  • 只能在宣告時賦值或利用建構子(Contructor)
  • const比較,readonly修飾完依然是一般成員(member variable)

實驗

使用VS2019

第一步 - 新增專案

  1. 新增一個ConsoleApp(圖1)

    Image Not Showing Possible Reasons
    • The image file may be corrupted
    • The server hosting the image is unavailable
    • The image path is incorrect
    • The image format is not supported
    Learn More →

  2. 對該專案的Solution新增一個Library,中文會叫做「程式庫」(圖2)

    Image Not Showing Possible Reasons
    • The image file may be corrupted
    • The server hosting the image is unavailable
    • The image path is incorrect
    • The image format is not supported
    Learn More →

    Image Not Showing Possible Reasons
    • The image file may be corrupted
    • The server hosting the image is unavailable
    • The image path is incorrect
    • The image format is not supported
    Learn More →

  3. 新增對程式庫的相依性(新增Reference) (圖3)

    Image Not Showing Possible Reasons
    • The image file may be corrupted
    • The server hosting the image is unavailable
    • The image path is incorrect
    • The image format is not supported
    Learn More →

第二步 - 建置

Lib

namespace ExampleLib { public class Constant { public static readonly string ReadOnlyString = "Readonly 1"; public const string ConstString = "Const 1"; } }

ConsoleApp

using System; using ExampleLib; namespace Example { class Program { static void Main(string[] args) { Console.WriteLine($"{Constant.ReadOnlyString}"); Console.WriteLine($"{Constant.ConstString}"); Console.ReadKey(); } } }

建置輸出後,沒意外會出現

Readonly 1 Const 1

第三步 - 更新

檔案總管

把ConsoleApp的檔案總管打開後,會看到 (圖4):

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

兩個主要的檔案,一個是執行檔(.exe),另一個程式庫(.dll)

再來更新我們程式庫(DLL)

namespace ExampleLib { public class Constant { public static readonly string ReadOnlyString = "Readonly 2"; public const string ConstString = "Const 2"; } }

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →
記得只要更新程式庫,不要直接按F5全部都建置了

然後回到ConsoleApp的資料夾,把程式庫建置出來的元件全部複製一份,複製到ConsoleApp的資料夾裡。

之後再次打開執行檔,會發現readonly跟著程式庫更新了,但const沒有

Readonly 2 Const 1

這就是上面所說的編譯時期常數執行時期常數

結論

  • 建議使用執行期常數(static readonly),而非編譯期常數(const)。

參考資料