1. 只有C#內置類型(int,double,long等)可以聲明為const;結果、類和數組不能聲明為const。
2. readonly 是在字段上使用的修飾符,直接以類名.字段訪問。
3. const 必須在申明中初始化。之後不能再修改。
4. readonly可以在申明中初始化,也可以在構造函數中初始化,其它情況不能修改。
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字段通過實例訪問 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在構造函數內初始化 { _weeks = 52; } public Calendar(int days,int weeks) //readonly在構造函數內初始化 { _days = days; _weeks = weeks; } public void setvalue(int days,int weeks) { // _days = days; 無法對只讀字段賦值 //_weeks = weeks; 無法對只讀字段賦值 } }