首页 > 代码库 > const 和 readonly 修饰符的用法

const 和 readonly 修饰符的用法

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; 无法对只读字段赋值        }    }

  

const 和 readonly 修饰符的用法