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

      

  • 相关阅读:
    Centos 7 KVM安装win10
    python3.6小程序
    linux随手笔记(Centos为主)
    python 3.6练习题(仿购物车)
    linux mint软件安装
    pacman详解及常见问题
    manjaro安装及设置
    Ansible安装及配置
    大盘分时黄白线
    渊海子平学习
  • 原文地址:https://www.cnblogs.com/liuqiyun/p/9512190.html
Copyright © 2011-2022 走看看