溫馨提示×

  • 首頁 > 
  • 問答 > 
  • 編程語言  > 
  • C#中protected關(guān)鍵字與base關(guān)鍵字的結(jié)合使用是怎樣的

C#中protected關(guān)鍵字與base關(guān)鍵字的結(jié)合使用是怎樣的

c#
小樊
85
2024-08-12 03:14:35
欄目: 編程語言

在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ù)成員。

0