首页
学习
活动
专区
圈层
工具
发布
社区首页 >专栏 >C# 中 const 和 readonly 关键字的区别和用法

C# 中 const 和 readonly 关键字的区别和用法

作者头像
郑子铭
发布2025-08-06 17:58:48
发布2025-08-06 17:58:48
4210
举报

前言

今天我们一起来讲讲 C# 中 const 和 readonly 关键字的区别和用法。

const 和 readonly 关键字区别

基本介绍

  • const(常量): 在C#中用于声明编译时常量,其值在编译时就必须确定,并且在程序生命周期内不可更改。
  • readonly(只读字段): 在C#中用于声明运行时常量,其值可以在声明时或构造函数中初始化,之后不可更改(可通过反射强制修改)。

const 和 readonly 异同点

对比维度

const

readonly

基础定义

编译时常量,值在编译期确定

运行时常量,值在运行时确定

初始化时机

必须在声明时初始化

可在声明时或构造函数中初始化

支持的数据类型

仅支持基元类型(int, float, char, bool等)、string和null引用

支持所有类型(包括自定义类和结构体)

默认值要求

必须显式初始化

不需要显示初始化,值类型默认零值,引用类型默认null

性能表现

零开销访问(直接编译到IL)

微小访问开销(作为实例/静态字段分配内存)

线程安全

天然线程安全

实例字段需注意可见性,静态字段线程安全

反射修改

无法通过反射修改

可通过反射强制修改

IL元数据标记

literal 标记

initonly 标记

使用场景

声明常量字段或本地常量,常量可以是数字、布尔值、字符串或 null 引用等

声明依赖注入对象、配置值、运行时计算值等

const 和 readonly 关键字使用

const 使用

代码语言:javascript
复制
    public enum UserRole
    {
        Admin,
        User,
        Guest
    }

    public class ConstAndReadonlyExercise
    {
        // const 初始化
        public const int MaxCount = 999;
        public const UserRole CurrentUserRole = UserRole.Admin;
    }

编译后 IL 代码:

  • literal 关键字:标记为字面量,值直接嵌入调用处的 IL。
代码语言:javascript
复制
  .field public static literal int32 MaxCount = int32(999) // 0x000003e7

  .field public static literal valuetype 'HelloDotNetGuide.CSharp语法.UserRole' CurrentUserRole = int32(0) // 0x00000000

readonly 使用

代码语言:javascript
复制
 // readonly 初始化
 public readonly string _applicationName = "HelloDotNetGuide";

 public ConstAndReadonlyExercise()
 {
     _applicationName = "HelloDotNetGuide_V2";
 }

 // 懒汉式单例模式示例
 private static ConstAndReadonlyExercise? _instance;
 private static readonly object _lockObj = new object();

 public static ConstAndReadonlyExercise Instance
 {
     get
     {
         if (_instance == null)
         {
             lock (_lockObj)
             {
                 _instance ??= new ConstAndReadonlyExercise();
             }
         }
         return _instance;
     }
 }

 /// <summary>
 /// 反射修改 readonly 字段的值
 /// </summary>
 public static void UpdateApplicationNameValue()
 {
     var instance = new ConstAndReadonlyExercise();
     Console.WriteLine($"初始值: {instance._applicationName}");
     // 输出: 初始值: HelloDotNetGuide_V2

     var field = instance.GetType().GetField("_applicationName");
     field.SetValue(instance, "HelloDotNetGuide_V3");

     Console.WriteLine($"修改后: {instance._applicationName}");
     // 输出: 修改后: HelloDotNetGuide_V3
 }

编译后 IL 代码:

  • initonly 关键字:标志被 CLR 识别为仅构造函数可写约束。
代码语言:javascript
复制
  .field public initonly string _applicationName

  .field private static class 'HelloDotNetGuide.CSharp语法.ConstAndReadonlyExercise' _instance
    .custom instance void [System.Runtime]System.Runtime.CompilerServices.NullableAttribute::.ctor(unsigned int8)
      = (01 00 02 00 00 ) // .....
      // unsigned int8(2) // 0x02

  .field private static initonly object _lockObj

  .method public hidebysig specialname rtspecialname instance void
    .ctor() cil managed
  {
    .maxstack 8

    // [25 9 - 25 70]
    IL_0000: ldarg.0      // this
    IL_0001: ldstr        "HelloDotNetGuide"
    IL_0006: stfld        string 'HelloDotNetGuide.CSharp语法.ConstAndReadonlyExercise'::_applicationName

    // [29 9 - 29 42]
    IL_000b: ldarg.0      // this
    IL_000c: call         instance void [System.Runtime]System.Object::.ctor()
    IL_0011: nop

    // [30 9 - 30 10]
    IL_0012: nop

    // [31 13 - 31 54]
    IL_0013: ldarg.0      // this
    IL_0014: ldstr        "HelloDotNetGuide_V2"
    IL_0019: stfld        string 'HelloDotNetGuide.CSharp语法.ConstAndReadonlyExercise'::_applicationName

    // [32 9 - 32 10]
    IL_001e: ret

  } // end of method ConstAndReadonlyExercise::.ctor

  .method public hidebysig static specialname class 'HelloDotNetGuide.CSharp语法.ConstAndReadonlyExercise'
    get_Instance() cil managed
  {
    .maxstack 2
    .locals init (
      [0] bool V_0,
      [1] object V_1,
      [2] bool V_2,
      [3] class 'HelloDotNetGuide.CSharp语法.ConstAndReadonlyExercise' V_3
    )

    // [37 13 - 37 14]
    IL_0000: nop

    // [38 17 - 38 39]
    IL_0001: ldsfld       class 'HelloDotNetGuide.CSharp语法.ConstAndReadonlyExercise''HelloDotNetGuide.CSharp语法.ConstAndReadonlyExercise'::_instance
    IL_0006: ldnull
    IL_0007: ceq
    IL_0009: stloc.0      // V_0

    IL_000a: ldloc.0      // V_0
    IL_000b: brfalse.s    IL_0040

    // [39 17 - 39 18]
    IL_000d: nop

    // [40 21 - 40 36]
    IL_000e: ldsfld       object 'HelloDotNetGuide.CSharp语法.ConstAndReadonlyExercise'::_lockObj
    IL_0013: stloc.1      // V_1
    IL_0014: ldc.i4.0
    IL_0015: stloc.2      // V_2
    .try
    {
      IL_0016: ldloc.1      // V_1
      IL_0017: ldloca.s     V_2
      IL_0019: call         void [System.Threading]System.Threading.Monitor::Enter(object, bool&)
      IL_001e: nop

      // [41 21 - 41 22]
      IL_001f: nop

      // [42 25 - 42 70]
      IL_0020: ldsfld       class 'HelloDotNetGuide.CSharp语法.ConstAndReadonlyExercise''HelloDotNetGuide.CSharp语法.ConstAndReadonlyExercise'::_instance
      IL_0025: brtrue.s     IL_0031
      IL_0027: newobj       instance void 'HelloDotNetGuide.CSharp语法.ConstAndReadonlyExercise'::.ctor()
      IL_002c: stsfld       class 'HelloDotNetGuide.CSharp语法.ConstAndReadonlyExercise''HelloDotNetGuide.CSharp语法.ConstAndReadonlyExercise'::_instance

      // [43 21 - 43 22]
      IL_0031: nop
      IL_0032: leave.s      IL_003f
    } // end of .try
    finally
    {

      IL_0034: ldloc.2      // V_2
      IL_0035: brfalse.s    IL_003e
      IL_0037: ldloc.1      // V_1
      IL_0038: call         void [System.Threading]System.Threading.Monitor::Exit(object)
      IL_003d: nop

      IL_003e: endfinally
    } // end of finally

    // [44 17 - 44 18]
    IL_003f: nop

    // [45 17 - 45 34]
    IL_0040: ldsfld       class 'HelloDotNetGuide.CSharp语法.ConstAndReadonlyExercise''HelloDotNetGuide.CSharp语法.ConstAndReadonlyExercise'::_instance
    IL_0045: stloc.3      // V_3
    IL_0046: br.s         IL_0048

    // [46 13 - 46 14]
    IL_0048: ldloc.3      // V_3
    IL_0049: ret

  } // end of method ConstAndReadonlyExercise::get_Instance

  .method public hidebysig static void
    UpdateApplicationNameValue() cil managed
  {
    .maxstack 3
    .locals init (
      [0] class 'HelloDotNetGuide.CSharp语法.ConstAndReadonlyExercise''instance',
      [1] class [System.Runtime]System.Reflection.FieldInfo 'field'
    )

    // [50 9 - 50 10]
    IL_0000: nop

    // [51 13 - 51 59]
    IL_0001: newobj       instance void 'HelloDotNetGuide.CSharp语法.ConstAndReadonlyExercise'::.ctor()
    IL_0006: stloc.0      // 'instance'

    // [52 13 - 52 68]
    IL_0007: ldstr        "初始值: "
    IL_000c: ldloc.0      // 'instance'
    IL_000d: ldfld        string 'HelloDotNetGuide.CSharp语法.ConstAndReadonlyExercise'::_applicationName
    IL_0012: call         string [System.Runtime]System.String::Concat(string, string)
    IL_0017: call         void [System.Console]System.Console::WriteLine(string)
    IL_001c: nop

    // [55 13 - 55 73]
    IL_001d: ldloc.0      // 'instance'
    IL_001e: callvirt     instance class [System.Runtime]System.Type [System.Runtime]System.Object::GetType()
    IL_0023: ldstr        "_applicationName"
    IL_0028: callvirt     instance class [System.Runtime]System.Reflection.FieldInfo [System.Runtime]System.Type::GetField(string)
    IL_002d: stloc.1      // 'field'

    // [56 13 - 56 61]
    IL_002e: ldloc.1      // 'field'
    IL_002f: ldloc.0      // 'instance'
    IL_0030: ldstr        "HelloDotNetGuide_V3"
    IL_0035: callvirt     instance void [System.Runtime]System.Reflection.FieldInfo::SetValue(object, object)
    IL_003a: nop

    // [58 13 - 58 68]
    IL_003b: ldstr        "修改后: "
    IL_0040: ldloc.0      // 'instance'
    IL_0041: ldfld        string 'HelloDotNetGuide.CSharp语法.ConstAndReadonlyExercise'::_applicationName
    IL_0046: call         string [System.Runtime]System.String::Concat(string, string)
    IL_004b: call         void [System.Console]System.Console::WriteLine(string)
    IL_0050: nop

    // [60 9 - 60 10]
    IL_0051: ret

  } // end of method ConstAndReadonlyExercise::UpdateApplicationNameValue
本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2025-08-03,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 DotNet NB 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 前言
  • const 和 readonly 关键字区别
    • 基本介绍
    • const 和 readonly 异同点
  • const 和 readonly 关键字使用
    • const 使用
    • readonly 使用
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档