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
基础教程推荐
- C# 从 List<List<int>> 中删除重 2022-01-01
- Moq It.Is<>不匹配 2022-01-01
- 如果有人提交恶意软件Nuget包怎么办? 2022-01-01
- Azure Functions:CosmosDBTrigger 未在 Visual Studio 中触发 2022-01-01
- WPF 模态进度窗口 2022-01-01
- 禁止输入少量字符,例如'<'、'&a 2022-01-01
- .NET SerialPort DataReceived 事件未触发 2022-01-01
- 我应该在后面的代码中直接使用 Linq To SQL 还是使 2022-01-01
- 如何使用 .Net 检查 Active Directory 服务器是否已启动并正在运行? 2022-01-01
- 当值可以是对象或空数组时反序列化 JSON 2022-01-01
