如何在 C# 中添加只读属性?


标记为“只读”的字段只能在对象构建时设置一次。它无法被更改 −

我们来看个例子。

class Employee {
   readonly int salary;

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

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

上面,我们已将 salary 字段设置为只读。

如果你要更改它,则会发生编译时错误。上述示例中显示了这一点。

现在,我们来看看如何检查一个数组是否只读 −

示例

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 次浏览

开启您的 职业生涯

完成课程并获取认证

开始
广告
© . All rights reserved.