分層繼承的 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");
         }
      }
   }
}

更新於:2020 年 6 月 19 日

3K+ 瀏覽量

開啟你的 職業生涯

透過完成課程獲取認證

開始
廣告