const 与 readonly

const vs. readonly(const 与 readonly)

本文介绍了const 与 readonly的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

今天我发现一篇文章,其中 const 字段称为 compile-time constantreadonly 字段称为 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

基础教程推荐