注意:const编译期常量是编译的时候就确定的,可以查看IL代码,是写死的。如果另一个程序集引用后,该程序集没有进行编译,则值不会改变。

看效果:

项目中有2个程序集:

c# 编译期常量const和运行时常量readonly

其中:常量在这个程序集中定义并初始化。

namespace ConstReadOnlyTest
{
    public class Class1
    {
        public const string a= "我是const常量.";
        public static string b = "我是static变量.";
        public readonly static string c = "我是readonly变量.";
    }
}

另外,在另一个程序集中引用:

 class ConstReadOnlyTest
    {
        static void Main(string[] args)
        {
            Console.WriteLine(Class1.a);
            Console.WriteLine(Class1.b);
            Console.WriteLine(Class1.c);
            Console.ReadKey();
        }
    }

看结果:

c# 编译期常量const和运行时常量readonly

接着,修改const的值:

namespace ConstReadOnlyTest
{
    public class Class1
    {
        public const string a= "我是const常量.1111";
        public static string b = "我是static变量.2222";
        public readonly static string c = "我是readonly变量.3333";
    }
}

编译后,把dll文件放到控制台的\bin\Debug中:

c# 编译期常量const和运行时常量readonly

接着,直接运行CAStudy.exe

c# 编译期常量const和运行时常量readonly

可以发现const常量的值未改变。

 

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-01-19
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-10-24
  • 2021-09-16
猜你喜欢
  • 2021-07-07
  • 2021-09-08
  • 2021-12-01
  • 2021-11-11
  • 2021-10-17
  • 2022-12-23
  • 2021-05-12
相关资源
相似解决方案