更新:2007 年 11 月
以下各節會比較 C# 和 Java 的修飾詞。
存取修飾詞
C# 的修飾詞與 Java 的十分類似,其中只有幾個些微的差異而已。類別的每個成員或類別本身都可以使用存取修飾詞來宣告,以便定義允許的存取範圍。不是在其他類別內宣告的類別只能指定 public 或 internal 修飾詞。巢狀類別和其他類別成員一樣,可以指定下列五個存取修飾詞中的任一個:
-
到處都可以看見
-
只能從衍生類別看見
-
只能在指定的類別內看見
-
只能在相同的組件內看見
protected internal
只有目前的組件或是衍生自包含類別的型別才能看見
public、protected 和 private 修飾詞
public 修飾詞可讓成員隨處可供使用,不論是在類別的內部或外部。protected 修飾詞表示將存取限制在包含類別內或在衍生自包含類別的類別內。private 修飾詞則表示只能從包含類別內存取。在 C# 中,預設的存取修飾詞是 private;在 Java 中則預設為從包含的封裝內到處皆可存取。
internal 修飾詞
internal 項目只能在目前組件內存取。一個 .NET Framework 中的組件大致等於 Java 的 JAR 檔案;它代表可用來建構其他程式的建置組塊 (Building Block)。
protected internal 修飾詞
只有目前的組件或是衍生自包含類別的型別才能看見 protected internal 項目。
sealed 修飾詞
在類別宣告中使用 sealed 修飾詞的類別與抽象類別完全相反:這種類別無法被繼承。您可以將類別標記為 sealed 以防止其他類別覆寫它的功能。密封 (Sealed) 類別當然不可能是抽象類別。同時請注意,struct 已隱含地密封,因此不能被繼承。sealed 修飾詞相當於在 Java 中使用 final 關鍵字來標記類別。
readonly 修飾詞
若要定義 C# 中的常數,請使用 const 或 readonly 修飾詞來替代 Java 的 final 關鍵字。這兩個 C# 修飾詞的分辨方法是,const 項目是在編譯時期處理,而 readonly 欄位值則是在執行階段指定。這意謂著,readonly 欄位可能是在類別建構函式中或是在宣告中設定的。例如,下列類別宣告了一個名為 IntegerVariable 的 readonly 變數,這個變數是在類別建構函式中初始化:
public class SampleClass
{
private readonly int intConstant;
public SampleClass () //constructor
{
// You are allowed to set the value of the readonly variable
// inside the constructor
intConstant = 5;
}
public int IntegerConstant
{
set
{
// You are not allowed to set the value of the readonly variable
// anywhere else but inside the constructor
// intConstant = value; // compile-time error
}
get
{
return intConstant;
}
}
}
class TestSampleClass
{
static void Main()
{
SampleClass obj= new SampleClass();
// You cannot perform this operation on a readonly field.
obj.IntegerConstant = 100;
System.Console.WriteLine("intConstant is {0}", obj.IntegerConstant); // 5
}
}
如果在靜態欄位上套用 readonly 修飾詞,那麼它應該在類別的靜態建構函式中被初始化。