如何在 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());
}
}
}
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
安卓系统
Python
C 语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP