温馨提示×

C#中protected方法如何被子类重写

c#
小樊
82
2024-09-08 03:32:24
栏目: 编程语言

在C#中,protected方法可以被子类重写。要重写一个基类的protected方法,您需要在子类中使用override关键字。这里有一个简单的例子来说明如何在C#中重写一个protected方法:

using System;

class BaseClass
{
    protected virtual void MyProtectedMethod()
    {
        Console.WriteLine("This is the base class's protected method.");
    }
}

class DerivedClass : BaseClass
{
    protected override void MyProtectedMethod()
    {
        Console.WriteLine("This is the derived class's overridden protected method.");
    }
}

class Program
{
    static void Main(string[] args)
    {
        DerivedClass obj = new DerivedClass();
        obj.MyProtectedMethod(); // 输出 "This is the derived class's overridden protected method."
    }
}

在这个例子中,我们有一个名为BaseClass的基类,它包含一个protected virtual方法MyProtectedMethod()。然后我们创建了一个名为DerivedClass的子类,它继承自BaseClass。在DerivedClass中,我们使用override关键字重写了MyProtectedMethod()方法。最后,在Main方法中,我们创建了一个DerivedClass对象并调用了其MyProtectedMethod()方法,输出结果显示子类已经成功地重写了基类的protected方法。

0