difference between ReadOnly and Const?

Possible Duplicate:
What is the difference between const and readonly?

are these interchangeable? can you show me code 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; ie, 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 ).

链接地址: http://www.djcxy.com/p/21218.html

上一篇: 我怎样才能在C#中获得相当于C ++的“const”?

下一篇: ReadOnly和Const之间的区别?