如何以 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

完成课程,获得认证

开始
广告