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

Multiple Inheritance ใน C# (การสืบทอดหลายคลาส)

C# ไม่รองรับ Multiple Inheritance โดยตรง แต่สามารถทำได้ผ่าน Interface

การ Implement ด้วย Interface

สร้าง 2 Interfaces:

public interface BaseOne { void display(); }
public interface BaseTwo { void display(); }

คลาสลูก Implement ทั้งสอง Interface:

public class ChildOne : BaseOne, BaseTwo
{
    public void display() { Console.WriteLine("Child Class!"); }
}

ตัวอย่างสมบูรณ์

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Demo
{
    class Program
    {
        static void Main(string[] args)
        {
            ChildOne c = new ChildOne();
            c.display();
            Console.ReadKey();
        }
    }

    public interface BaseOne { void display(); }
    public interface BaseTwo { void display(); }
    public class ChildOne : BaseOne, BaseTwo
    {
        public void display() { Console.WriteLine("Child Class!"); }
    }
}