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.