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 }
复制代码

 

posted @   小五义  阅读(500)  评论(0编辑  收藏  举报
编辑推荐:
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
阅读排行:
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?
点击右上角即可分享
微信分享提示