• C# base关键字:调用父类成员方法

    在上一节《C# VS2015类图的使用》中介绍的继承关系的类图中可以看出,在每个类中都有 Print 方法,即子类和父类中有同名的方法。

    那么这种方式是方法的重载吗?答案是否定的,方法重载是指方法名相同而方法的参数不同的方法。

    在 C# 语言中子类中定义的同名方法相当于在子类中重新定义了一个方法,在子类中的对象是调用不到父类中的同名方法的,调用的是子类中的方法。

    因此也经常说成是将父类中的同名方法隐藏了。

    【实例 1】在 Main 方法中分别创建前面编写过的 Person、Teacher 以及 Student 类的对 象,并调用其中的 Print 方法。

    根据题目要求,代码如下。

    class Program
    {
        static void Main(string[] args)
        {
            Person person = new Person();
            Console.WriteLine("Person类的Print方法打印内容");
            person.Print();
            Student student = new Student();
            Console.WriteLine("Student类的Print方法打印内容");
            student.Print();
            Teacher teacher = new Teacher();
            Console.WriteLine("Teacher类的Print方法打印内容");
            teacher.Print();
        }
    }

    执行上面的代码,效果如下图所示。

    使用不同类的对象调用Print方法

更多...

加载中...