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