const string 和 static readonly string的区别

当跨assemblies的时候要特别注意两者的区别, 请看这篇文章

if the scope of your constant is limited to just one assembly, class, or smaller (you can define a const inside a method), this is not a big deal.  However, if the const is visible outside the assembly it is defined in, we must be wary!  Because the const’s value is substituted at compile time, this means that if the assembly that defines the const changes its value, but the calling assembly isn’t recompiled, then the calling assembly will still see the original value.

Let’s illustrate.  Assume a class library called Shapes.DLL that defines this:

   1: public class Circle
   2: {
   3:     public const double Pi = 3.14;
   4:     
   5:     // ...
   6: }

Now let’s assume a separate program called Drawing.EXE adds a reference to Shapes.DLL and uses the const:

   1: public static class Drawing
   2: {
   3:     public static void Main()
   4:     {
   5:         Console.WriteLine(“Pi is: “ + Circle.Pi);
   6:     }
   7: }

If we run this, we get:

   1: Pi is 3.14

Now let’s say during the QA process someone decides that this value of Pi is not precise enough and changes the definition:

   1: public const double Pi = 3.1415927;

And they rebuild the Shapes.DLL and just drop it into the deployment directory for Drawing.EXE without rebuilding it.  What happens if we run Drawing.EXE again without recompiling?  We get:

   1: Pi is 3.14

Whoa!  Even though we changed the value of Pi in our referenced assembly and deployed it to where Drawing.EXE expected it and Drawing.EXE loaded it, it still prints 3.14.  This is because const is a compile-time substitution.  Thus, if you change the value of a const, it will not be picked up until the code using it is recompiled as well.  If we recompile and run Drawing.EXE, we will get:

   1: Pi is 3.1415927

Thus, const should be used mainly for values that are not subject to change, or freely if the scope of the const is limited to the same assembly or smaller.

posted @   dragonpig  阅读(866)  评论(0编辑  收藏  举报
编辑推荐:
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· 展开说说关于C#中ORM框架的用法!
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
点击右上角即可分享
微信分享提示