C#中const 和 readonly 修飾符的用法詳解
1. 只有C#內(nèi)置類型(int,double,long等)可以聲明為const;結(jié)果、類和數(shù)組不能聲明為const。
2. readonly 是在字段上使用的修飾符,直接以類名.字段訪問。
3. const 必須在申明中初始化。之后不能再修改。
4. readonly可以在申明中初始化,也可以在構(gòu)造函數(shù)中初始化,其它情況不能修改。
namespace const_and_readonly { class Program { static void Main(string[] args) { Console.WriteLine("Half a year have {0} Moths", Calendar.Moths/2); //直接類名.字段訪問const字段 Calendar test1 = new Calendar(); Console.WriteLine("Every year has {0} weeks and {1} days", test1._weeks, test1._days);//readonly字段通過實(shí)例訪問 Calendar test2 = new Calendar(31, 4); Console.WriteLine("January has {0} weeks and {1} days", test2._weeks ,test2 ._days); Console.ReadKey(); } } class Calendar { public const int Moths = 12; //const必須在聲明中初始化 public readonly int _days=365; //readonly在聲明中初始化 public readonly int _weeks; public Calendar() //readonly在構(gòu)造函數(shù)內(nèi)初始化 { _weeks = 52; } public Calendar(int days,int weeks) //readonly在構(gòu)造函數(shù)內(nèi)初始化 { _days = days; _weeks = weeks; } public void setvalue(int days,int weeks) { // _days = days; 無法對(duì)只讀字段賦值 //_weeks = weeks; 無法對(duì)只讀字段賦值 } }
以上所述是小編給大家介紹的C#中const 和 readonly 修飾符的用法詳解,希望對(duì)大家有所幫助,如果大家有任何疑問請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)腳本之家網(wǎng)站的支持!
- C#中const和readonly的用法比較
- 淺談Java中的final關(guān)鍵字與C#中的const, readonly關(guān)鍵字
- 淺談c#中const與readonly區(qū)別
- C#中const用法詳解
- 深入探討C#中的const、readonly關(guān)鍵字
- C#基礎(chǔ)知識(shí)系列八const和readonly關(guān)鍵字詳細(xì)介紹
- C++中const的實(shí)現(xiàn)細(xì)節(jié)介紹(C,C#同理)
- c#.net中const和readonly的區(qū)別
- C#基礎(chǔ):基于const與readonly的深入研究
- C#中 const 和 readonly 的不同
- C# 中const,readonly,static的使用小結(jié)
相關(guān)文章
C#使用迭代法實(shí)現(xiàn)Fibnaci數(shù)列
這篇文章主要介紹了C#使用迭代法實(shí)現(xiàn)Fibnaci數(shù)列的方法,較為詳細(xì)的分析了Fibnaci數(shù)列的原理與迭代法實(shí)現(xiàn)技巧,需要的朋友可以參考下2015-05-05關(guān)于Unity中RectTransform與transform的區(qū)別
這篇文章主要介紹了Unity中RectTransform與transform的區(qū)別,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2022-01-01C# WebApi Get請(qǐng)求方式傳遞實(shí)體參數(shù)的方法示例
這篇文章主要給大家介紹了關(guān)于C# WebApi Get請(qǐng)求方式傳遞實(shí)體參數(shù)的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家學(xué)習(xí)或者使用C#具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面來一起學(xué)習(xí)學(xué)習(xí)吧2019-04-04C#驗(yàn)證碼識(shí)別基礎(chǔ)方法實(shí)例分析
這篇文章主要介紹了C#驗(yàn)證碼識(shí)別基礎(chǔ)方法實(shí)例分析,較為詳細(xì)的總結(jié)了C#驗(yàn)證碼的實(shí)現(xiàn)思路及具體步驟,并對(duì)實(shí)現(xiàn)思路進(jìn)行了總結(jié)歸納,具有很好的實(shí)用價(jià)值,需要的朋友可以參考下2014-09-09