How is the use of protected implemented in C#?
In C#, ‘protected’ is an access modifier that specifies only derived classes can access members. Protected members are visible within the same class or derived classes, but not visible in instances of the class.
By using the protected modifier, the internal implementation details of a class can be protected while still providing extension points for derived classes. Subclasses can inherit the protected members of the parent class and use them in their own implementations.
Here are examples of how to use the “protected” feature:
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方法
}
}
In the example above, BaseClass has a protected field and a protected method. DerivedClass inherits from BaseClass, allowing it to access and use the protected members in BaseClass.