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

C# และ Multiple Inheritance

C# ไม่รองรับ Multiple Inheritance (สืบทอดจากหลาย Base class) โดยตรง ใช้ Interfaces แทน

รูปแบบการใช้ Interface แทน Multiple Inheritance

  1. สร้าง Interface ที่มีเมธอดที่ต้องการ
  2. Class ให้ Implement Interface นั้นๆ ได้หลาย Interface

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

using System;
namespace MyInheritance {
    class Shape {
        public void SetWidth(int w) { width = w; }
        public void SetHeight(int h) { height = h; }
        protected int width;
        protected int height;
    }
    public interface IPaintCost {
        int GetCost(int area);
    }
    class Rectangle : Shape, IPaintCost {
        public int GetArea() { return width * height; }
        public int GetCost(int area) { return area * 80; }
    }
    class RectangleDemo {
        static void Main(string[] args) {
            Rectangle rect = new Rectangle();
            rect.SetWidth(8);
            rect.SetHeight(10);
            int area = rect.GetArea();
            Console.WriteLine("Total area: {0}", area);
            Console.WriteLine("Total paint cost: ${0}", rect.GetCost(area));
            Console.ReadKey();
        }
    }
}

ผลลัพธ์:

Total area: 80
Total paint cost: $6400

จุดสำคัญ: Class เดียวสามารถ Implement Interface ได้หลายตัว (class A : I1, I2, I3) แต่สืบทอด Class ได้เพียงตัวเดียว