Partial Classes

Written by 650710551 Thananton Pojanawongpanit

Partial Class ก็เหมือนกับการที่เราตัด Slime เป็นหลายๆส่วน แต่ก็สามารถนำมันกลับมารวมกันได้เป็นอันเดียวกัน

  • โดยปกติแล้ว Class ไม่สามารถใช้ชื่อ Class เดียวกันได้เนื่องจากจะทำให้เกิดข้อผิดพลาด และ เราไม่สามารถใช้ Method จาก Class เดิมได้ ถ้าเราไม่ได้ทำการ inheritance หรือ import เขามาใช้ตาม Concept ของแต่ละภาษา

  • Partial Class สามารถทำให้เราใช้ชื่อคลาสเดียวกันได้และยังสามารถใช้ Method ที่อยู่ในคลาสที่ชื่อเดียวกันได้ด้วย และ สามารถใช้ Partial class ในการแยก Class ออกเป็น 2 ไฟล์ได้แต่ว่ายังสามารถใช้ Method ที่อยู่ในชื่อคลาสเดียวกันได้โดยใช้ keyword ที่มีชื่อว่า partial โดยที่ตอน Compile ไปแล้วทั้ง 2 Class ก็จะรวมกันแล้วสามารถเรียก object มา 1 ตัวแล้วสามารถใช้งาน Method ที่มาจากทั้ง 2 Class ที่มีชื่อเหมือนกันจากทั้ง 2 ไฟล์ได้โดยมี partial เชื่อมอยู่

Keyword

partial

Syntax

public partial class class_name{}

เทียบกับ Partial class ในภาษาอื่น

  • Partial class ใน ภาษา Java ไม่มีการรองรับ Partial class โดยตรงแต่สามารถใช้ interface หรือ inheritance แทนได้ แต่ว่าจะอยู่ในไฟล์เดียวกันไม่สามารถแยกไฟล์กันได้

  • Partial Class ใน ภาษา C ไม่รองรับแนวคิดแบบ OOP ส่วนใหญ่จะใช้ Struct แทน

  • Partial Class ใน ภาษา Python ไม่มีการรองรับ Partial Class โดยตรงแต่สามารถใช้การแบ่งออกเป็นหลาย Modules แล้วใช้การ import ไฟล์เข้ามาแทน หรือ จะใช้การ inheritance ก็ได้

Example

การเขียน Partial Class

C#

ไฟล์ที่ 1

public partial class PartialClass{
    public void HelloWorld(){
        Console.WriteLine("Hello, world!");
    }
}

ไฟล์ที่ 2

public partial class PartialClass{
    public void HelloMonkey(){
        Console.WriteLine("Hello , Monkey");
    }
}

เมื่อ Compile แล้วสามารถเรียกใช้ทั้ง 2 Method ได้ใน main

class Program{
    static void Main(string[] args){
        PartialClass pc = new PartialClass();
        pc.HelloWorld();
        pc.HelloMonkey();
    }
}

Java

ใช้ Inheritance เข้ามาใช้แทน

interface Animal{
   public void sound();
}

class Dog implements Animal{
    public void sound(){
         System.out.println("Bark") ; 
    }
    public void run(){
         System.out.println("Run Run");
    }
}

C

ใช้ Struct เข้ามาทดแทน

#include <stdio.h>
struct MyStruc{
    int Num ;
    char Letter ;
} ;
void main(){
    struct MyStruc s ;
    s.Num = 1 ;
    s.Letter = 'X';   
    printf("My number: %d\n", s.Num);
    printf("My letter: %c\n", s.Letter);
}

Python

ใช้การแบ่ง Module

file ที่ 1

class MyClass:
    def Eiei(self):
        print("Hello class 2")

file ที่ 2

from file1 import MyClass

def eieiei(self):
    print("Hello class 1")

Reference

Video

Slide

Last updated