C# 层次继承示例


层次继承中,多个类从基类继承。

在本示例中,我们的基类是Father

class Father {
   public void display() {
      Console.WriteLine("Display...");
   }
}

它具有SonDaughter作为派生类。我们来看如何在继承中添加派生类 −

class Son : Father {
   public void displayOne() {
      Console.WriteLine("Display One");
   }
}

示例

以下是 C# 中实现层次继承的完整示例 −

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Inheritance {
   class Test {
      static void Main(string[] args) {
         Father f = new Father();
         f.display();
         Son s = new Son();
         s.display();
         s.displayOne();
         Daughter d = new Daughter();
         d.displayTwo();
         Console.ReadKey();
      }
      class Father {
         public void display() {
            Console.WriteLine("Display...");
         }
      }
      class Son : Father {
         public void displayOne() {
            Console.WriteLine("Display One");
         }
      }
      class Daughter : Father {
         public void displayTwo() {
            Console.WriteLine("Display Two");
         }
      }
   }
}

更新日期: 19-06-2020

3K+ 浏览量

开启你的 职业生涯

通过完成课程获得认证

开始学习
广告
© . All rights reserved.