Const 与 Readonly 使用总结

在以往的开发过程中一直使用Const来定义常量,很少注意到Readonly的使用,因为总感觉Const的使用已经足够了。而就在这两天,在阅读SqlHelper的代码时,再次看到了Readonly的使用,而且感觉很别扭。如果按Const来说,定义了常量后,常量在使用时是不允许再次改变的。而Readonly不然,在构造函数中进行了再次赋值。由于对Readonly使用的迷惑,本着学习的态度,总结了Const 与 Readonly 使用,供以后参考:

名称

静态常量(Const)

动态常量/只读变量(Readonly)

使用范围

全局和局部

全局

初始值

定义时必须赋初始值

定义时可不赋值

赋值方式

定义时赋值

定义时赋值、构造函数中赋值

访问方式

类型访问

实例对象访问

Static

不能和Static同时使用

可以和Static 同时使用,使用后,如果想在构造函数中赋初始值,必须使用静态无参构造函数。

应用类型

只能应用值类型和string类型

任意类型

实例(vs2008)

 1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Text;
5
6 namespace ConstAndReadonly
7 {
8 class Program
9 {
10 static void Main(string[] args)
11 {
12 Console.WriteLine(ConstTest.str); //通过类型访问
13 ReadonlyTest rt = new ReadonlyTest("123456"); //通过实例对象访问,并通过构造函数赋值
14 Console.WriteLine(rt.str);
15 Console.WriteLine(rt.strnull);
16 string[] str1 = {"1","2","3","4","5","6" };
17 ReadonlyTest rt2 = new ReadonlyTest(str1); //通过构造函数赋予数组
18 Console.WriteLine(rt2.str1.Count());
19 Console.ReadLine();
20 }
21 }
22 class ConstTest
23 {
24 public const string str = "Const Test"; //无法改变
25 }
26 class ReadonlyTest
27 {
28 public readonly string str = "Readonly Test";
29 public readonly string strnull; //未赋予初始值,默认赋值null;
30 public readonly string[] str1;
31 public ReadonlyTest(string s)
32 {
33 this.strnull = this.str;
34 this.str = s;
35 }
36 public ReadonlyTest(string[] s)
37 {
38 this.str1 = s;
39 }
40 }
41 }
原文地址:https://www.cnblogs.com/xiaowuyi/p/constandreadonly.html