在C#中,protected關(guān)鍵字用于定義受保護(hù)的成員,只能被其自身或者派生類的實(shí)例訪問。而base關(guān)鍵字用于引用基類的成員或者調(diào)用基類的構(gòu)造函數(shù)。
當(dāng)在派生類中需要訪問基類的受保護(hù)成員時(shí),可以使用protected關(guān)鍵字來定義基類中的成員,并使用base關(guān)鍵字來訪問或調(diào)用基類中的成員。例如:
class BaseClass
{
protected int protectedField;
protected void ProtectedMethod()
{
Console.WriteLine("BaseClass ProtectedMethod");
}
}
class DerivedClass : BaseClass
{
public void AccessProtectedMember()
{
base.protectedField = 10; // 訪問基類的受保護(hù)字段
base.ProtectedMethod(); // 調(diào)用基類的受保護(hù)方法
}
}
在上面的例子中,DerivedClass派生自BaseClass,通過使用base關(guān)鍵字可以在DerivedClass中訪問和調(diào)用BaseClass中的受保護(hù)成員。