const 和 static readonly 區別?

作者: Clark Zheng  發布時間: 2008-09-04 10:44  閱讀: 10573 次  推薦: 2   原文鏈接   [收藏]  

系列文章導航:

靜態成員和非靜態成員的區別?

const 和 static readonly 區別?

extern 是什么意思?

abstract 是什么意思?

internal 修飾符起什么作用?

sealed 修飾符是干什么的?

override 和 overload 的區別?

什么是索引指示器?

new 修飾符是起什么作用?

this 關鍵字的含義?

可以使用抽象函數重寫基類中的虛函數嗎?

C#基礎概念之密封類,屬性訪問器,接口

類和結構的區別?

C#基礎概念之抽象類,接口,接口多繼承

別名指示符是什么?

如何手工釋放資源?

C#基礎概念之P/Invoke,StringBuilder 和 String

explicit 和 implicit 的含義?

params 有什么用?

什么是反射?

 

 

2.const 和 static readonly 區別?

答:

const: 用const修飾符聲明的成員叫常量,是在編譯期初始化并嵌入到客戶端程序 static readonly: 用static readonly修飾符聲明的成員依然是變量,只不過具有和常量類似的使用方法:通過類進行訪問、初始化后不可以修改。但與常量不同的是這種變量是在運行期初始化 。

示例:

測試類:

 

Code
using System;
using System.Collections.Generic;
using System.Text;
 
namespace Example02Lib
{
    public class Class1
    {
        public const String strConst = "Const";
        public static readonly String strStaticReadonly = "StaticReadonly";
        //public const String strConst = "Const Changed";
        //public static readonly String strStaticReadonly = "StaticReadonly Changed";
    }
}

 

 

客戶端代碼:

 

Code
using System;
using System.Collections.Generic;
using System.Text;
using Example02Lib; 
namespace Example02
{    
    class Program    
    {        
        static void Main(string[] args)        
        {            
            //修改Example02中Class1的strConst初始值后,只編譯Example02Lib項目            
            //然后到資源管理器里把新編譯的Example02Lib.dll拷貝Example02.exe所在的目錄,執行Example02.exe            
            //切不可在IDE里直接調試運行因為這會重新編譯整個解決方案!!             
            //可以看到strConst的輸出沒有改變,而strStaticReadonly的輸出已經改變            
            //表明Const變量是在編譯期初始化并嵌入到客戶端程序,而StaticReadonly是在運行時初始化的            
            Console.WriteLine("strConst : {0}", Class1.strConst);            
            Console.WriteLine("strStaticReadonly : {0}", Class1.strStaticReadonly);             
            Console.ReadLine();        
        }    
    }
}

 

結果:
strConst : Const
strStaticReadonly : StaticReadonly

 

修改后的示例:

測試類:

 

Code
using System;
using System.Collections.Generic;
using System.Text;
 
namespace Example02Lib
{
    public class Class1
    {
        //public const String strConst = "Const";
        //public static readonly String strStaticReadonly = "StaticReadonly";
        public const String strConst = "Const Changed";
        public static readonly String strStaticReadonly = "StaticReadonly Changed";
    }
}

結果

strConst : Const
strStaticReadonly : StaticReadonly Changed

 

 

 

 

2
0
 
 
 

文章列表

arrow
arrow
    全站熱搜
    創作者介紹
    創作者 大師兄 的頭像
    大師兄

    IT工程師數位筆記本

    大師兄 發表在 痞客邦 留言(0) 人氣()