常量与只读 [英] const vs. readonly

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

问题描述

今天,我发现,其中一个常量字段被称为一个项目的编译时常的而只读字段被称为的运行时常的。这两个短语来源于有效的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的变量,其值是酒吧,并且该值是只读的,在这里它是一个变量,在没有业务不断。甲只读变量仍然是一个变数,它不可能是一个常数。可变区和恒定是相互排斥的。

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?

推荐答案

正如你指出,这个词是不是在语言规范等,所以使用;怪那本书!我把它叫做一个只读域,因为那是它是什么 - 那里的只读在这里的定义涉及到初始化/构造,且仅限于常规code 。例如,即使只读字段是可变...

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 presumably取代了现场负荷连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)

这篇关于常量与只读的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆