const、readonly及静态构造的用法

来源:互联网 发布:vs2015写c语言 编辑:程序博客网 时间:2024/06/11 01:02
public class Test{    //const为编译时常量    public const string _cStr = "Const_String";    //readonly为运行时常量    public readonly string _rStr;    public static readonly string _srStr;    //静态构造不能出现访问修饰符,并且不能够传递任何参数,在程序执行过程中,只会执行一次    static Test()    {        Console.WriteLine("静态构造,让我先行,程序执行过程中,只调用这唯一的一次!!");        _srStr = "只能在静态构造中赋值(编译时赋值)";    }    public Test(string str)    {        Console.WriteLine("普通构造,可执行多次!!");        _rStr = str;    }   }public class Tmp{    public Test test;    public Tmp(string str)    {        test = new Test(str);    }}class Program{    static void Main(string[] args)    {        Console.WriteLine(Test._cStr);        //Console.WriteLine(Test._srStr);        Test test = new Test("ctor_Readonly_String");        Tmp tmp = new Tmp("Test静态构造不调用!");        Console.WriteLine( test._rStr + "," + Test._srStr);        Console.ReadKey();    }}

运行图解:
这里写图片描述

原创粉丝点击