如何以 C# 新增只讀屬性?


標記為“只讀”的欄位只能在構造物件時設定一次。不可更改−

讓我們看一個例子。

class Employee {
   readonly int salary;

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

   void UpdateSalary() {
      //salary = 50000; // Compile error
   }
}

以上,我們將薪水欄位設定為了只讀。

如果您要更改它,則會導致編譯時錯誤。在上面的示例中顯示了這一點。

現在讓我們看看如何檢查陣列是否只讀−

示例

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace lower {
   class Program {
      static void Main(string[] args) {
         Array arr = Array.CreateInstance(typeof(String), 3);
         arr.SetValue("Maths", 0);
         arr.SetValue("Science", 1);
         arr.SetValue("PHP", 2);

         Console.WriteLine("isReadOnly: {0}",arr.IsReadOnly.ToString());
      }
   }
}

更新於: 2020-06-21

211 次瀏覽

Kickstart Your Career

完成課程,獲得認證

開始
廣告
© . All rights reserved.