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

คีย์เวิร์ด base ใน C#: เทียบเท่า super ใน Java

ใน Java ใช้คีย์เวิร์ด super อ้างถึงคลาสแม่ (Superclass) ใน C# ใช้คีย์เวิร์ด base แทน ใช้เพื่อเข้าถึง Constructor, เมธอด, หรือฟิลด์ของคลาสฐาน

การใช้งาน base

  • base() - เรียก Constructor ของคลาสแม่
  • base.Method() - เรียกเมธอดของคลาสแม่
  • base.Field - เข้าถึงฟิลด์ของคลาสแม่ (เมื่อถูกซ่อนโดยคลาสลูก)

ตัวอย่าง: เข้าถึงฟิลด์ที่ถูกซ่อน (Field Hiding)

using System;

public class Animal
{
    public string Color = "Brown";
}

public class Reptile : Animal
{
    // ซ่อนฟิลด์ Color ของ Animal (Field Hiding)
    public string Color = "Green";
    
    public void Display()
    {
        Console.WriteLine("สีจาก base (Animal): " + base.Color);
        Console.WriteLine("สีจาก Reptile: " + Color);
    }
}

public class Demo
{
    public static void Main()
    {
        Reptile rep = new Reptile();
        rep.Display();
    }
}

ผลลัพธ์

สีจาก base (Animal): Brown
สีจาก Reptile: Green

ตัวอย่าง: เรียก Constructor แม่

public class Animal
{
    public string Name { get; set; }
    
    public Animal(string name)
    {
        Name = name;
        Console.WriteLine("Animal Constructor");
    }
}

public class Dog : Animal
{
    public string Breed { get; set; }
    
    public Dog(string name, string breed) : base(name) // เรียก base constructor
    {
        Breed = breed;
        Console.WriteLine("Dog Constructor");
    }
}

ความแตกต่าง Java super vs C# base

คุณสมบัติJava superC# base
Constructorsuper()base()
Methodsuper.method()base.Method()
Fieldsuper.fieldbase.Field
Static memberเข้าถึงได้เข้าถึงไม่ได้ (compile error)