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

Gọi Base Class Constructor từ Child Class trong C#: Từ khóa base

Tóm tắt 2 từ khóa

Từ khóaMục đíchVị trí
thisGọi constructor khác trong cùng classConstructor initializer
baseGọi constructor của base class (parent)Constructor initializer

Cú pháp


// Gọi base constructor
public ChildClass(parameters) : base(baseParameters) 
{
    // Child constructor body
}

// Gọi constructor khác cùng class
public ChildClass(parameters) : this(otherParameters) 
{
    // Child constructor body
}

Ví dụ: Gọi Base Constructor


public class DemoBase 
{
    public DemoBase(int first, int second, int third) 
    {
        Console.WriteLine("Base class Constructor");
        Console.WriteLine($"{first} {second} {third}");
    }
}

public class Demo : DemoBase 
{
    // Gọi base constructor với 3 tham số
    public Demo(int first, int second, int third) 
        : base(first, second, third) 
    {
        Console.WriteLine("Derived class Constructor");
        Console.WriteLine($"{first} {second} {third}");
    }
}

class Program 
{
    static void Main() 
    {
        Demo obj = new Demo(1, 2, 3);
        Console.ReadLine();
    }
}

Kết quả

Base class Constructor
1 2 3
Derived class Constructor
1 2 3

Quy tắc quan trọng

  1. Base constructor chạy TRƯỚC derived constructor body.
  2. Nếu base class có constructor không tham số → derived class KHÔNG cần gọi base() explicit (tự động gọi).
  3. Nếu base class KHÔNG có constructor không tham số → derived class BẮT BUỘC gọi base(...) với tham số phù hợp.
  4. Không thể gọi base() và this() cùng lúc trong một constructor.

Ví dụ: Base class không có parameterless constructor


public class Animal 
{
    public string Name { get; }
    
    // Chỉ có constructor có tham số
    public Animal(string name) 
    {
        Name = name;
        Console.WriteLine($"Animal created: {Name}");
    }
}

public class Dog : Animal 
{
    public string Breed { get; }
    
    // BẮT BUỘC gọi base(name)
    public Dog(string name, string breed) 
        : base(name) 
    {
        Breed = breed;
        Console.WriteLine($"Dog created: {Breed}");
    }
}

// Sử dụng
var dog = new Dog("Buddy", "Golden Retriever");
// Output:
// Animal created: Buddy
// Dog created: Golden Retriever

Constructor Chaining (this) trong cùng class


public class Demo 
{
    public Demo() 
    {
        Console.WriteLine("Parameterless constructor");
    }
    
    public Demo(int a) : this() 
    {
        Console.WriteLine($"1 param: {a}");
    }
    
    public Demo(int a, int b) : this(a) 
    {
        Console.WriteLine($"2 params: {a}, {b}");
    }
    
    public Demo(int a, int b, int c) : this(a, b) 
    {
        Console.WriteLine($"3 params: {a}, {b}, {c}");
    }
}

// new Demo(1, 2, 3) gọi chuỗi:
// Parameterless constructor
// 1 param: 1
// 2 params: 1, 2
// 3 params: 1, 2, 3

Kết hợp this + base


public class Base 
{
    public Base(int x) { Console.WriteLine($"Base({x})"); }
    public Base(int x, int y) { Console.WriteLine($"Base({x},{y})"); }
}

public class Derived : Base 
{
    public Derived(int a) : base(a) { }           // Gọi Base(int)
    public Derived(int a, int b) : base(a, b) { } // Gọi Base(int,int)
    public Derived(int a, int b, int c) : this(a, b) { } // Gọi Derived(int,int) → Base(int,int)
}

Best Practices

  • Luôn cung cấp parameterless constructor cho base class nếu có thể (dễ derive).
  • Dùng this() chaining để tránh duplicate code khởi tạo.
  • Validation logic đặt ở constructor "cha" nhất (có nhiều tham số nhất).
  • Tránh logic phức tạp trong constructor - cân nhắc Factory Method.