一、常量、只读字段、静态字段和静态只读字段对比
1 public class modelclass
2 {
3 //常量在定义时必须赋初始值
4 //public const string constfield;
5 public const string constfield = "常量";
6 public readonly string readfield = "只读字段";
7 public static string staticfield = "静态字段";
8 public static readonly string staticreadfield = "静态只读字段";
9
10 public modelclass()
11 {
12 //常量的值在编译时就必须知道,而构造函数在运行时才执行,所以常量不能通过构造函数赋初值;而只读字段的值可以在运行时才决定。
13 //constfield = "不能在构造函数中初始化常量";
14 readfield = "构造函数初始化只读字段";
15 }
16 static modelclass()
17 {
18 //constfield = "不能在静态构造函数中初始化常量";
19 staticfield = "静态构造函数初始化静态字段";
20 staticreadfield = "静态构造函数初始化静态只读字段";
21 }
22
23 public string method()
24 {
25 //在方法中定义常量并使用
26 const string constlocal = "局部常量";
27 string result = constlocal;
28 return result;
29 //readonly和static都不能在方法中使用
30 }
31 public static string staticmethod()
32 {
33 //在静态方法中定义常量并使用
34 const string constlocal = "局部常量";
35 string result = constlocal;
36 return result;
37 //readonly和static都不能在静态方法中使用
38 }
39 }
40 public class realizeobject
41 {
42 public void realize()
43 {
44 //常量、静态字段和静态只读字段是类级别的
45 string value1 = modelclass.constfield;
46 string value2 = modelclass.staticfield;
47 string value3 = modelclass.staticreadfield;
48 //只读字段是对象级别的
49 modelclass model = new modelclass();
50 string value4 = model.readfield;
51 //常量、只读字段和静态只读字段的值不能被修改
52 //modelclass.constfield = "不可以修改常量的值";
53 //model.readfield = "不可以修改只读字段的值";
54 //modelclass.staticreadfield = "不可以修改静态只读字段的值";
55 modelclass.staticfield = "可以修改静态字段的值";
56 }
57 }
常量、只读字段、静态字段和静态只读字段对比表:

常量、只读字段、静态字段和静态只读字段适用数据:
1、常量适用于定义时就已知且不能改变的数据。
2、只读字段适用于通过第三方在运行时赋值且不能改变的数据(对象独享)。
3、静态只读字段适用于通过第三方在运行时赋值且不能改变的数据(对象共享)。
4、静态字段适用于对象共享的数据。
深爱某女zi