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
        */
    }
    

      

  • 相关阅读:
    渣渣的python的上路
    【tyvj 2038】诡异的数学题
    codeforces_733_A
    NOIP2011 选择客栈
    NOIP 2012 同余方程
    灵渊(seals.cpp/c/pas)
    NOIP 2012 开车旅行
    Mybatis初步详细配置
    SpringMVC之编程式校验
    Spring整合MyBaytis
  • 原文地址:https://www.cnblogs.com/liuqiyun/p/9512190.html
Copyright © 2011-2022 走看看