hf

导航

 

Constants

A constant is a symbol that has a never-changing value . The compiler saves the constant’s value in the assembly’s metadata at compile time.

You can define a constant only for types that your compiler considers primitive types . However, C# also allows you to define a  constant variable of a non-primitive type if you set the value to null(what’s the use?).

Constants are always considered to be static members.

When code refers to a constant symbol, compilers look up the symbol in the metadata of the assembly that defines the constant, extract the constant’s value, and embed the value in the emitted Intermediate Language (IL) code . Because a constant’s value is embedded directly in code, constants don’t require any memory to be allocated for them at runtime . In addition,you can’t get the address of a constant and you can’t pass a constant by reference . Be careful when using another assembly’s constants(versioning problem).

Fields

Field Modifiers:

CLR Term C# Term Description
Static static  
Instance (default)  
InitOnly readonly

The field can be written to only by code contained in a constructor method .

Volatile volatile

Code that accessed the field is not subject to some thread-unsafe optimizations .

For type fields, the dynamic memory required to hold the field’s data is allocated inside the type object, which is created when the type is loaded into an AppDomain , which typically happens the first time any method that references the type is JIT–compiled . For instance fields, the dynamic memory to hold the field is allocated when an instance of the type is constructed .

Because fields are stored in dynamic memory, their value can be obtained at runtime only . Fields also solve the versioning problem that exists with constants .

C# treats initializing a field inline as shorthand syntax for initializing the field in a constructor .

When a field is of a reference type and the field is marked as readonly, it is the reference that is immutable, not the object that the field refers to .

posted on 2010-07-13 17:33  hf  阅读(192)  评论(0)    收藏  举报