Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C#

Kế thừa đa trọng (Multiple Inheritance) trong C#

C# không hỗ trợ kế thừa đa trọng trực tiếp, nhưng có thể triển khai qua interface.

Tạo 2 interface:

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

Lớp con triển khai cả 2 interface:

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

Ví dụ hoàn chỉnh

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!"); }
    }
}