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


复制代码 代码如下:

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

namespace ConsoleApplication1
{
    /// <summary>
    /// 作者:it小金
    /// 功能: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()//静态构造函数,类实例化之前调用执行,且只执行一次
        {

            b = 2;//因为是只读字段,所以只能在构造函数中进行初始化,且改只读字段为static类型,所以需在静态构造函数中进行赋值
        }
        void aa()
        {
            //a = 1;错误
            //b=1;错误
        }

       
    }
}


« 
» 
快速导航

Copyright © 2016 phpStudy | 豫ICP备2021030365号-3