zoukankan      html  css  js  c++  java
  • readonly和const区别

    https://docs.microsoft.com/zh-cn/dotnet/csharp/language-reference/keywords/readonly

    备注

    The readonly keyword is different from the const keyword. const field can only be initialized at the declaration of the field.readonly field can be initialized either at the declaration or in a constructor. Therefore, readonly fields can have different values depending on the constructor used. Also, while a const field is a compile-time constant, the readonly field can be used for runtime constants as in the following example:

    class Age
    {
        readonly int year;
        Age(int year)
        {
            this.year = year;
        }
        void ChangeYear()
        {
            //year = 1967; // Compile error if uncommented.
        }
    }
    

      

    class SampleClass
    {
        public int x;
        // Initialize a readonly field
        public readonly int y = 25;
        public readonly int z;
    
        public SampleClass()
        {
            // Initialize a readonly instance field
            z = 24;
        }
    
        public SampleClass(int p1, int p2, int p3)
        {
            x = p1;
            y = p2;
            z = p3;
        }
    
        static void Main()
        {
            SampleClass p1 = new SampleClass(11, 21, 32);   // OK
            Console.WriteLine($"p1: x={p1.x}, y={p1.y}, z={p1.z}");
            SampleClass p2 = new SampleClass();
            p2.x = 55;   // OK
            Console.WriteLine($"p2: x={p2.x}, y={p2.y}, z={p2.z}");
        }
        /*
         Output:
            p1: x=11, y=21, z=32
            p2: x=55, y=25, z=24
        */
    }
    

      

  • 相关阅读:
    品质家居 生活之魅
    珍爱之礼 美妙感受
    节日礼物清单
    2014新年礼物推荐清单
    Python元组
    python更新列表
    Python列表
    Python 数字
    Python字符串
    python标准数据类型
  • 原文地址:https://www.cnblogs.com/liuqiyun/p/9512190.html
Copyright © 2011-2022 走看看