• c#只读字段和常量的区别,以及静态构造函数的使用 .


    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;

    namespace ConsoleApplication1
    {
        /// <summary>
        /// 功能:c#只读字段和常量的区别,以及静态构造函数的使用
        /// </summary>
        class Program
        {
            static void Main(string[] args)
            {
                Console.WriteLine(test.a);
                Console.WriteLine(test.b);
                Console.Read();
               
            }

       
        }
        public class test
        {
            public static readonly int b;//只读字段可以使用static关键字,只读字段可以不在声明时进行初始化赋值,只读字段只能在声明时或“同类的”构造函数里进行初始化赋值。
           public const int a=1;//常量不可以使用static关键字,常量必须在定义的时候进行初始化赋值
          
           static test()//静态构造函数,类实例化之前(编译时,C#是即时编译的)调用执行,且只执行“一次”
            {
              
                b = 2;   //只读字段可以在构造函数中进行初始化赋值,且该只读字段为static类型,所以需要在静态构造函数中进行赋值
            }
            void aa()
            {
                //a = 1;错误
                //b=1;错误
            }

           
        }
    }

  • 相关阅读:
    大型网站数据库架构分析
    Mysql 存储引擎中InnoDB与Myisam的主要区别
    设计模式培训之一:为什么要用单例模式?
    架构师成长之路
    hdoj1257 最少拦截系统
    hdoj2571 命运
    hdoj1010 Temperor of the bone
    hdoj1175 连连看
    ny220 推桌子
    ny168 房间安排
  • 原文地址:https://www.cnblogs.com/changbaishan/p/3480528.html
Copyright © 2020-2023  润新知