温馨提示×

c#中protected的使用方法是什么

c#
小亿
104
2024-03-07 16:55:30
栏目: 编程语言

在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中有一个protected字段和一个protected方法,DerivedClass继承了BaseClass,并且可以访问和使用BaseClass中的protected成员。

0