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 @ 2011-03-25 16:48 dragonpig 阅读(...) 评论(...) 编辑 收藏