问题描述
有有一个私人常量
变量或C#(A 私有静态只读
变量比其他之间的差异其分配常量
编译时表达)?
Is there a difference between having a private const
variable or a private static readonly
variable in C# (other than having to assign the const
a compile-time expression)?
因为他们都是私人的,没有链接与其他图书馆。所以它会作出任何区别吗?它可以使例如性能差异?实习字符串?什么相似?
Since they are both private, there is no linking with other libraries. So would it make any difference? Can it make a performance difference for example? Interned strings? Anything similar?
推荐答案
那么,你可以使用consts的属性,因为它们存在的编译时间。你无法预测一个静态只读变量的值,因为 .cctor
可从配置等初始化。
Well, you can use consts in attributes, since they exist as compile time. You can't predict the value of a static readonly variable, since the .cctor
could initialize it from configuration etc.
在使用方面,常量被烧到调用代码。这意味着,如果你重新编译的库的DLL来更改公开不变,但不改变消费者,那么他的消费者将仍然使用原来的值。随着只读变量不会出现这种情况。这样做的翻转是常数(非常,非常轻微)更快,因为它简单地将值(而不是必须去引用它)。
In terms of usage, constants are burnt into the calling code. This means that if you recompile a library dll to change a public constant, but don't change the consumers, then he consumers will still use the original value. With a readonly variable this won't happen. The flip of this is that constants are (very, very slightly) quicker, since it simply loads the value (rather than having to de-reference it).
重新实习;虽然你可以手动做到这一点,这是最常用的文字的编译器/运行功能;如果您通过字面初始化一个只读域:
Re interning; although you can do this manually, this is most commonly a compiler/runtime feature of literals; if you init a readonly field via a literal:
someField = "abc";
那么ABC
将被拘禁。如果从配置读它,它不会是。由于常量字符串必须是文字,也将被扣留,但访问不同:再次,从外地读书是去引用,而不是一个的。
then the "abc"
will be interned. If you read it from config, it won't be. Because a constant string must be a literal, it will also be interned, but it is accessed differently: again, reading from the field is a de-reference, rather than a ldstr
.
这篇关于有没有在C#中的私人const和私人只读变量之间的差异?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!