C# const和static readonly區(qū)別淺談
C#語言有很多值得學(xué)習(xí)的地方,這里我們主要介紹C# const和static readonly區(qū)別,包括介紹用const修飾符聲明的成員叫常量和static readonly修飾符聲明的成員依然是變量等方面。
C# const和static readonly區(qū)別
const: 用const修飾符聲明的成員叫常量,是在編譯期初始化并嵌入到客戶端程序
static readonly: 用static readonly修飾符聲明的成員依然是變量,只不過具有和常量類似的使用方法:通過類進行訪問、初始化后不可以修改。但與常量不同的是這種變量是在運行期初始化。
C# const和static readonly區(qū)別示例:
- 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";
- }
- }
客戶端代碼:
- 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所在的目錄,
執(zhí)行Example02.exe- //切不可在IDE里直接調(diào)試運行因為這會重新編譯整個解決方案??!
- //可以看到strConst的輸出沒有改變,而strStaticReadonly的輸出已經(jīng)改變
- //表明Const變量是在編譯期初始化并嵌入到客戶端程序,而StaticReadonly是在運行時初始化的
- Console.WriteLine("strConst : {0}", Class1.strConst);
- Console.WriteLine("strStaticReadonly : {0}", Class1.strStaticReadonly);
- Console.ReadLine();
- }
- }
- }
修改后的示例:
- 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";
- }
- }
【編輯推薦】