Const 与 Readonly 使用总结

简介: 在以往的开发过程中一直使用Const来定义常量,很少注意到Readonly的使用,因为总感觉Const的使用已经足够了。而就在这两天,在阅读SqlHelper的代码时,再次看到了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 }

 

目录
相关文章
|
10天前
|
弹性计算 关系型数据库 微服务
基于 Docker 与 Kubernetes(K3s)的微服务:阿里云生产环境扩容实践
在微服务架构中,如何实现“稳定扩容”与“成本可控”是企业面临的核心挑战。本文结合 Python FastAPI 微服务实战,详解如何基于阿里云基础设施,利用 Docker 封装服务、K3s 实现容器编排,构建生产级微服务架构。内容涵盖容器构建、集群部署、自动扩缩容、可观测性等关键环节,适配阿里云资源特性与服务生态,助力企业打造低成本、高可靠、易扩展的微服务解决方案。
1218 5
|
9天前
|
机器学习/深度学习 人工智能 前端开发
通义DeepResearch全面开源!同步分享可落地的高阶Agent构建方法论
通义研究团队开源发布通义 DeepResearch —— 首个在性能上可与 OpenAI DeepResearch 相媲美、并在多项权威基准测试中取得领先表现的全开源 Web Agent。
1182 87
|
10天前
|
云栖大会
阿里云云栖大会2025年9月24日开启,免费申请大会门票,速度领取~
2025云栖大会将于9月24-26日举行,官网免费预约畅享票,审核后短信通知,持证件入场
1779 13
|
19天前
|
人工智能 运维 安全
|
3天前
|
资源调度
除了nrm-pm,还有哪些工具可以管理多个包管理器的源?
除了nrm-pm,还有哪些工具可以管理多个包管理器的源?
231 127
|
3天前
|
前端开发
Promise的then方法返回的新Promise对象有什么特点?
Promise的then方法返回的新Promise对象有什么特点?
169 2