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

ตัวอย่าง C# Single Inheritance

Single Inheritance (การสืบทอดเดี่ยว) คือ Derived class สืบทอดจาก Base class เพียงหนึ่งระดับ

โครงสร้าง

Father (Base class)
    ↓ inherits
Son (Derived class)

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

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MyAplication {
    class Demo {
        static void Main(string[] args) {
            // Father class
            Father f = new Father();
            f.Display();
            // Son class
            Son s = new Son();
            s.Display();      // เรียกจาก Father
            s.DisplayOne();   // เมธอดของตัวเอง
            Console.ReadKey();
        }
        class Father {
            public void Display() {
                Console.WriteLine("Display");
            }
        }
        class Son : Father {
            public void DisplayOne() {
                Console.WriteLine("DisplayOne");
            }
        }
    }
}

ผลลัพธ์

Display
Display
DisplayOne

คำอธิบาย: Son สืบทอด Display() จาก Father และมี DisplayOne() ของตัวเอง สร้างออบเจ็กต์ Son แล้วเรียกทั้งสองเมธอดได้