开发者

difference between ReadOnly and Const? [duplicate]

This question already has answers here: Closed 12 years ago.

Possible Duplicate:

What is the difference between const and readonly?

are these interchangeable? can you show me c开发者_Go百科ode on how you would apply the two?


No, they aren't.

A const field is literal value embedded in the assembly.
Only primitive values (strings and numbers) can be const, and they are evaluated at compile time.
When you reference a const field, the compiler embeds the literal value of the field. Therefore, if use use a const from another assembly, and the other assembly is recompiled with a different value, your assembly will only use the new value if you recompile it against the new version.


A readonly field is a normal field that cannot be changed outside the constructor.


Const can't perform evaluations whereas readonly can on initialization. (ie you could read in a value for a readonly variable from a config file or based on some other parameter that is known at runtime, const can only be set to something known at compile time)


A member of any type can be readonly. It simply means the member cannot be reassigned after the construction of the containing class; i.e., it cannot be set to a new object with the = operator. Mutable classes such as collections can still be modified with respect to their members; it's just that, if you have a readonly member that is a collection, it cannot be assigned to an entirely new collection after construction.

A const is not so different from a literal (like 5): it represents an unchanging value and thus only really makes sense in the context of specifying a value (as opposed to an object).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜