const vs. readonly(const 与 readonly)
问题描述
今天我发现一篇文章,其中 const
字段称为 compile-time constant 而 readonly
字段称为 runtime constant.这两个短语来自《Effective C#》.我在 MSDN 和语言规范中进行了搜索,没有找到关于 运行时常量.
Today I found an article where a const
field is called compile-time constant while a readonly
field is called runtime constant. The two phrases come from 《Effective C#》. I searched in MSDN and the language spec, find nothing about runtime constant.
没有冒犯,但我不认为 运行时常量 是一个合适的短语.
No offensive but I don't think runtime constant is a proper phrase.
private readonly string foo = "bar";
创建一个名为foo"的变量,其值为bar",值为只读,这里是一个变量,对constant
没有任何作用.只读变量仍然是变量,它不能是常量.变量和常量是互斥的.
creates a variable named "foo", whose value is "bar", and the value is readonly, here it is a variable, no business on constant
. A readonly variable is still a variable, it can't be a constant. Variable and constant are mutually exclusive.
也许这个问题太过分了,我还是想听听别人的意见.你怎么看?
Maybe this question goes overboard, still I want to listen to others' opinions. What do you think?
推荐答案
正如您自己注意到的,该术语未在语言规范等中使用.所以;怪那本书!我将其称为只读字段",因为它就是这样 - 这里的只读"定义与初始化程序/构造函数相关,并且仅限于常规代码.例如,即使是只读字段也是可变的...
As you yourself note, that term is not used in the language specification etc. So; blame that book! I would call it a "readonly field", because that is what it is - where the definition of "readonly" here relates to the initializer/constructor, and is limited to regular code. For example, even readonly fields are changeable...
// how to annoy your colleagues...
typeof(string).GetField("Empty").SetValue(null, " ");
(注意,这不再适用于最近的 CLR 版本 - JIT 可能会用 ldstr 替换字段加载 - 但它确实在很长一段时间内都有效)
(Note, this no longer works on recent CLR versions - the JIT presumably replaces the field-load with a ldstr - but it genuinely did for a very long time)
(更多真正对对象执行此操作的原因与反序列化有关)
(more genuine reasons to do this on objects relate to deserialization)
这篇关于const 与 readonly的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:const 与 readonly


- MoreLinq maxBy vs LINQ max + where 2022-01-01
- 输入按键事件处理程序 2022-01-01
- C# 中多线程网络服务器的模式 2022-01-01
- Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式 2022-01-01
- WebMatrix WebSecurity PasswordSalt 2022-01-01
- 在哪里可以找到使用中的C#/XML文档注释的好例子? 2022-01-01
- 带有服务/守护程序应用程序的 Microsoft Graph CSharp SDK 和 OneDrive for Business - 配额方面返回 null 2022-01-01
- 良好实践:如何重用 .csproj 和 .sln 文件来为 CI 创建 2022-01-01
- C#MongoDB使用Builders查找派生对象 2022-09-04
- 如何用自己压缩一个 IEnumerable 2022-01-01