[C#] const
vs readonly
const
- 編譯時期常數
- 只能用於primitive type或refernce type
- 只能在宣告時賦值
- 在class內,被視為靜態成員(static member)
readonly
- 執行時期常數
- 只能在宣告時賦值或利用建構子(Contructor)
- 與
const
比較,readonly
修飾完依然是一般成員(member variable)
實驗
使用VS2019
第一步 - 新增專案
-
新增一個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 →
-
對該專案的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 →
-
新增對程式庫的相依性(新增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
ConsoleApp
建置輸出後,沒意外會出現
第三步 - 更新
檔案總管
把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)
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
沒有
這就是上面所說的編譯時期常數和執行時期常數
結論
- 建議使用執行期常數(static readonly),而非編譯期常數(const)。
參考資料