C#でのprotectedの使い方は何ですか?
C#において、protectedはアクセス修飾子の一種であり、派生クラスだけがメンバーにアクセスできるよう指定されています。protectedメンバーは同じクラスや派生クラスでは可視ですが、クラスのインスタンスでは不可視です。
protected修飾子を使用すると、クラスの内部実装の詳細を保護することができ、同時に派生クラスへの拡張ポイントを提供することができます。サブクラスは親クラスのprotectedメンバーを継承し、自身の実装で使用することができます。
以下はprotectedの使用例です:
public class BaseClass
{
protected int protectedField;
protected void ProtectedMethod()
{
Console.WriteLine("This is a protected method in the base class");
}
}
public class DerivedClass : BaseClass
{
public void AccessProtectedMember()
{
protectedField = 10; // 可以访问父类的protected字段
ProtectedMethod(); // 可以调用父类的protected方法
}
}
上記の例では、BaseClassには1つのprotectedフィールドと1つのprotectedメソッドがあり、DerivedClassはBaseClassを継承しており、BaseClassのprotectedメンバーにアクセスおよび使用することができます。