当跨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:
Now let’s assume a separate program called Drawing.EXE adds a reference to Shapes.DLL and uses the const:
If we run this, we get:
Now let’s say during the QA process someone decides that this value of Pi is not precise enough and changes the definition:
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:
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:
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.