1、使用 const
關鍵字來聲明某個常量字段或常量局部變量。常量字段和常量局部變量不是變量並且不能修改。 常量可以為數字、布爾值、字符串或 null 引用(Constants can be numbers, Boolean values, strings, or a null reference)。
下面代碼會報編譯錯誤:
public const DateTime myDateTime = new DateTime(2018,05,23,0,0,0);
2、不允許在常數聲明中使用 static
修飾符。
static const string a = "a"; //Error
報錯:不能將變量“a”標記為static。
3、常數可以參與常數表達式,如下所示:
public const int c1 = 5; public const int c2 = c1 + 100;
4、readonly 關鍵字與 const
關鍵字不同:const 字段只能在該字段的聲明中初始化。readonly字段可以在聲明或構造函數中初始化。因此,根據所使用的構造函數,`readonly` 字段可能具有不同的值。

1 class ReadOnly 2 { 3 private readonly string str; 4 public ReadOnly() 5 { 6 str = @"ReadOnly() 構造函數"; 7 Console.WriteLine(str); 8 } 9 public ReadOnly(int i) 10 : this() 11 { 12 str = @"ReadOnly(int i) 構造函數"; 13 Console.WriteLine(str); 14 str = @"asd"; 15 Console.WriteLine(str); 16 } 17 }
調用: ReadOnly ro = new ReadOnly(1);
輸出:
5、static
如果 static
關鍵字應用於類,則類的所有成員都必須是靜態的。不能通過實例引用靜態成員。 然而,可以通過類型名稱引用它。
public class MyBaseC { public struct MyStruct { public static int x = 100; } }
若要引用靜態成員 x
,除非可從相同范圍訪問該成員,否則請使用完全限定的名稱 MyBaseC.MyStruct.x。