新聞中心
C#語(yǔ)言有很多值得學(xué)習(xí)的地方,這里我們主要介紹C# const和static readonly區(qū)別,包括介紹用const修飾符聲明的成員叫常量和static readonly修飾符聲明的成員依然是變量等方面。

讓客戶(hù)滿(mǎn)意是我們工作的目標(biāo),不斷超越客戶(hù)的期望值來(lái)自于我們對(duì)這個(gè)行業(yè)的熱愛(ài)。我們立志把好的技術(shù)通過(guò)有效、簡(jiǎn)單的方式提供給客戶(hù),將通過(guò)不懈努力成為客戶(hù)在信息化領(lǐng)域值得信任、有價(jià)值的長(zhǎng)期合作伙伴,公司提供的服務(wù)項(xiàng)目有:主機(jī)域名、虛擬空間、營(yíng)銷(xiāo)軟件、網(wǎng)站建設(shè)、太子河網(wǎng)站維護(hù)、網(wǎng)站推廣。
C# const和static readonly區(qū)別
const: 用const修飾符聲明的成員叫常量,是在編譯期初始化并嵌入到客戶(hù)端程序
static readonly: 用static readonly修飾符聲明的成員依然是變量,只不過(guò)具有和常量類(lèi)似的使用方法:通過(guò)類(lèi)進(jìn)行訪(fǎng)問(wèn)、初始化后不可以修改。但與常量不同的是這種變量是在運(yùn)行期初始化。
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";
- }
- }
客戶(hù)端代碼:
- using System;
- using System.Collections.Generic;
- using System.Text;
- using Example02Lib;
- namespace Example02
- {
- class Program
- {
- static void Main(string[] args)
- {
- //修改Example02中Class1的strConst初始值后,只編譯Example02Lib項(xiàng)目
- //然后到資源管理器里把新編譯的Example02Lib.dll拷貝Example02.exe所在的目錄,
執(zhí)行Example02.exe- //切不可在IDE里直接調(diào)試運(yùn)行因?yàn)檫@會(huì)重新編譯整個(gè)解決方案!!
- //可以看到strConst的輸出沒(méi)有改變,而strStaticReadonly的輸出已經(jīng)改變
- //表明Const變量是在編譯期初始化并嵌入到客戶(hù)端程序,而StaticReadonly是在運(yùn)行時(shí)初始化的
- 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";
- }
- }
【編輯推薦】
- C# const常量詳細(xì)介紹
- C# Lambda表達(dá)式學(xué)習(xí)筆記
- C#隱式類(lèi)型局部變量經(jīng)驗(yàn)總結(jié)
- 調(diào)用C# Thread.Start()方法
- C# CheckStatus()方法
本文名稱(chēng):C# const和static readonly區(qū)別淺談
網(wǎng)站URL:http://www.5511xx.com/article/cdojddc.html


咨詢(xún)
建站咨詢(xún)
