C# 中的最終區域性變數


若要將 final 設定為區域性變數,請在 C# 中使用 readonly 關鍵字,因為無法實現 final 關鍵字。

readonly 允許僅將值分配給變數一次。在建立物件期間,只能設定一次標記為“readonly”的欄位。無法更改。

讓我們看一個示例。在下面,我們設定了 empCount 欄位為只讀,一旦分配就不能更改它。

示例

class Department {
   readonly int empCount;

   Employee(int empCount) {
      this. empCount = empCount;
   }

   void ChangeCount() {
      //empCount = 150; // Compile error
   }
}

更新於:2020 年 6 月 21 日

1 千次瀏覽

開啟你的職業生涯

完成課程以獲得認證

開始使用
廣告