readonly用于字段,意思是:字段只能在初始化时候赋值,在随后的使用中,字段的值不能再改变。举个列子:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
public class TestReadonly { private int readonly int x; //X是只读字段 public TestReadonly() { // 只能在初始化时,对只读字段赋值 x = 100; } pubilc int GetX() { //这个语句是错误的,因为x不能被再次赋值,x是只读的(readonly),而 // 下面的语句试图改变x的值。 //x = x +100; //这个语句是正确的,因为语句执行后,x的值没有变 int x1 = x + 100; return x1; } } |