关于const/readonly/static readonly

 

比较:

  1. constreadonly的值一旦初始化则都不再可以改写;
  2. const只能在声明时初始化;readonly既可以在声明时初始化也可以在构造器中初始化;
  3. const隐含static,不可以再写static constreadonly则不默认static,如需要可以写static readonly
  4. const是编译期静态解析的常量(因此其表达式必须在编译时就可以求值);readonly则是运行期动态解析的常量;
  5. const既可用来修饰类中的成员,也可修饰函数体内的局部变量;readonly只可以用于修饰类中的成员。

场景:

 

 class Test
    
{
        
//对于恒不改变的值我们可以用const, 并且该字段为静态。编译后该值不再会改变。
        public const double PI = 3.1415926;
        
//对于在短期内不会改变但每隔一段时间需要修改可用static readonly。比如密码。
        public static readonly string password;
        
//对于实例而言,假设每个实例需要有自己的某个属性(代号),这些属性一旦赋值即不可更改即可用readonly。这样可以避免误修改。
        public readonly Guid guid;

        
static Test()
        
{
            
//密码从外部配置文件读取,当密码改变后只需要修改配置文件而不需要修改代码并重新编译。
            password = System.Configuration.ConfigurationManager.AppSettings["password"];
        }


        
public Test()
        
{
            guid 
= new Guid();
        }


        
public void Method()
        
{
            
const int myConst = 3;
            
//
            
//the following code cannot pass compiling.
            
//readonly int rd = 4;
            
//
        }

     }

 

posted @ 2009-07-02 16:25  AdaColor  阅读(410)  评论(0)    收藏  举报