Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

ตัวอย่าง C# Multi-level Inheritance

Multi-level Inheritance (การสืบทอดหลายระดับ) เกิดขึ้นเมื่อ Derived class ถูกสร้างจาก Derived class อีกตัว

ตัวอย่างคลาสิก: Grandfather (ปู่) → Father (พ่อ) → Son (ลูก)

โครงสร้างคลาส

Grandfather (Base)
    ↓ inherits
Father (Derived from Grandfather)
    ↓ inherits
Son (Derived from Father)

ตัวอย่างโค้ดเต็ม

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Demo {
    class Son : Father {
        public void DisplayTwo() {
            Console.WriteLine("Son..");
        }
        static void Main(string[] args) {
            Son s = new Son();
            s.Display();      // จาก Grandfather
            s.DisplayOne();   // จาก Father
            s.DisplayTwo();   // จาก Son
            Console.Read();
        }
    }
    class Grandfather {
        public void Display() {
            Console.WriteLine("Grandfather...");
        }
    }
    class Father : Grandfather {
        public void DisplayOne() {
            Console.WriteLine("Father...");
        }
    }
}

ผลลัพธ์

Grandfather...
Father...
Son..

คำอธิบาย: Son สืบทอดจาก Father ซึ่งสืบทอดจาก Grandfather ทำให้ Son เข้าถึงเมธอดของทั้งสองระดับได้