层次继承的 C# 示例

来源:这里教程网 时间:2026-02-21 16:18:59 作者:

层次继承的 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");
         }
      }
   }
}

相关推荐