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

      

  • 相关阅读:
    wxpython 浏览器框架
    wxpython 开发播放器
    Docker学习(三)——Docker镜像使用
    Docker学习(二)——Docker容器使用
    SSL/TLS协议
    Https原理及证书管理
    证书及证书管理
    Docker学习(一)——安装docker
    Linux系统中安装软件方法总结
    Linux下删除的文件如何恢复
  • 原文地址:https://www.cnblogs.com/liuqiyun/p/9512190.html
Copyright © 2011-2022 走看看