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.

转载于:https://www.cnblogs.com/dragonpig/archive/2011/03/25/1995641.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值