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;錯誤
??????? }
???????
??? }
}