将 public const 与字符串一起使用是否安全?
我听说这样做是一个坏主意:
public const double Pi = 3;
因为后来当我意识到我需要将其更改为 3.14
时,其他程序集将无法看到更改,直到它们也重新编译为止。因此readonly
将是更好的选择。
这同样适用于字符串吗?例如,
public const string Name = "Buh";
它只是恒定的参考,对吧?或者编译器在这里做了一些聪明的事情?
字符串文字“Buh”是否内联到其他程序集中?或者只是内联对“Buh”的引用?
I have heard that it is a bad idea to do something like:
public const double Pi = 3;
because later when I realise I need to change it to 3.14
, other assembillies will not be able to see the change until they are recompiled too. Therefore readonly
would be a better choice.
Does the same apply to strings? For example with
public const string Name = "Buh";
it is only the reference that is constant, right? Or does the compiler do something clever here?
Is the the string literal, "Buh" inlined into other assemblies? Or is only the reference to "Buh" inlined?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
问题是,编译器在生成 IL 之前,会将所有常量替换为常量的实际值,因此它是什么类型并不重要。如果它是字符串、双精度、整数或其他任何值,则使用 const 的程序集将继续使用旧值,直到重新编译它们,因为编译后的 IL 不知道任何存在的常量。它只知道值本身,就像您直接对其进行硬编码一样。
另一方面,readonly 的评估方式与其他非只读字段类似,因此无论只读字段的类型如何,其他程序集都将看到更改。
The thing is that the compiler, before the IL is generated, will replace all constants with the actual value of the constant, so it does not matter what type it is. If it's a string, double, int or whatever, the assemblies that use the const will continue to use the old value untill they are recompiled, since the compiled IL has no knowledge of any constant ever existing. It just know about the value itself, just like if you had hardcoded it directly.
readonly on the other hand is evaluated like other non-readonly fields, and therefore changes will be seen by other assemblies regardless of the type of the readonly field.
http://weblogs.asp.net/psteele/archive/2004 /01/27/63416.aspx
const
是编译时的,所以你是对的:如果将来可能发生变化,请使用readonly
!http://weblogs.asp.net/psteele/archive/2004/01/27/63416.aspx
const
is compile-time, so you're right: usereadonly
if it might change in the future!字符串是不可变的,所以它与 double 相同。
strings are immutable, so it is the same as for double.