const 和 readonly 修饰符的用法

发布时间:2019-05-02  栏目:Python  评论:0 Comments

1.
只有C#停放类型(int,double,long等)能够阐明为const;结果、类和数组无法宣称为const。

  1. readonly 是在字段上选择的修饰符,直接以类名.字段访问。

  2. const 必须在注解中初阶化。之后无法再修改。

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

    }

  

留下评论

网站地图xml地图