C# 中的最終區域性變數
要用 read-only 關鍵字為區域性變數設定最終,因為無法實現 final 關鍵字。
readonly 允許僅將值一次性分配給變數。在構造物件期間,標記為“read-only”的欄位只能設定一次。它無法更改。
我們舉個例子。下面,我們設定了 empCount 欄位為只讀,一旦分配就無法更改。
示例
class Department { readonly int empCount; Employee(int empCount) { this. empCount = empCount; } void ChangeCount() { //empCount = 150; // Compile error } }
廣告