Page cover image

this Keyword

ธนพัฒน์ สถิตย์กุลรัตน์ 650710548

ในภาษา C# this keyword คำว่า this เป็นคำที่ใช้ช่วยในการอ้างอิงถึง วัตถุ(object)ที่ถูกสร้างจากคลาสนั้นหรือเรียกว่า Instance คำว่า this สามารถใช้ได้ในหลายสถานการณ์ เช่น

1. ใช้ this เพื่ออ้างถึง Instance ของคลาส

Example

using System;
class Pet {
    public string name = "Aomsin"; 

    public void SetNameWithoutThis(string name)
    {
        name = name;
    }

    public void SetNameWithThis(string name)
    {
        this.name = name;
    }

    public string GetName()
    {
        return name;
    }
}

class SetPet { 
    public static void Main()
    {
        Pet obj = new Pet();
        
        obj.SetNameWithoutThis("Dollar");
        Console.WriteLine("SetNameWithoutThis: " + obj.GetName());

        obj.SetNameWithThis("Dollar");
        Console.WriteLine("SetNameWithThis: " + obj.GetName());
    }
}

OUTPUT

SetNameWithoutThis: aomsin
SetNameWithThis: Dollar

อธิบาย CODE

จาก code ด้านบนเป็นการใช้this เพื่ออ้างอิง field name ของ instance คลาสปัจจุบัน โดยใช้Methodแสดงให้เห็นความต่างของการใช้ this และไม่ใช้ this เริ่มแรกเราให้ field name มีค่าเป็น aomsin อยากทำการเปลี่ยนเป็น Dollar ผ่านMethodทั้งสอง สังเกตุได้ว่าMethodที่ไม่มีการใช้ this ไม่มีผลต่อ field name ของคลาส Pet เพราะมันไม่ได้ใช้ this เพื่ออ้างอิง field ของ instance แต่ถ้ามีการใช้ this จะส่งผลทำให้ field name ของ instance ของคลาส Pet ที่ถูกสร้างขึ้นมาเปลี่ยนจาก aomsin เป็น Dollar

2. ใช้ this เพื่อเรียกใช้ constructor ตัวอื่นภายในคลาสเดียวกัน

Example

using System;
class Pet {
    public string name;
    public int age;

    public Pet(string name)
    {
        this.name = name;
        this.age = 1;
    }

    public Pet(string name, int age) : this(name)
    {
        this.age = age;
    }

    public void DisplayInfo()
    {
        Console.WriteLine("Name: " + name + ", Age: " + age);
    }
}

class SetPet {
    public static void Main()
    {
        Pet pet1 = new Pet("Aomsin");
        pet1.DisplayInfo();

        Pet pet2 = new Pet("Dollar", 5);
        pet2.DisplayInfo();
    }
}

OUTPUT

Name: Aomsin, Age: 1
Name: Dollar, Age: 5

อธิบาย CODE

ใน constructor แรกรับพารามิเตอร์ name กำหนดค่าให้กับ this.name และกำหนดค่า age เป็น 1 โดยอัตโนมัติเมื่อไม่ได้ระบุอายุมา ส่วน constructor ที่สองใช้ this(name) เพื่อเรียกใช้ constructor แรกที่มีพารามิเตอร์ name ก่อน จากนั้นจึงกำหนดค่า age แยกต่างหากภายใน constructor ที่สอง เมื่อส่ง name เข้าไปอย่างเดียวจะเรียกใช้ constructor ที้่รับชื่อเท่านั้น จึงทำให้มีอายุเป็น 1 อัตโนมัติ และหากส่งทั้ง name และ age จะเรียกใช้ constructor ทีี่รับทั้งชื่อและอายุ

3. ใช้ this เพื่อเรียกใช้เมธอดคลาสปัจจุบัน

Example

using System;
public class Pet
{
    public string name;

    public void SetName(string name)
    {
        this.name = name;
    }

    public void DisplayPetInfo()
    {
        Console.WriteLine("Pet's Name: " + this.name);
        this.Hello();
    }

    public void Hello()
    {
        Console.WriteLine("Hello! I am " + name);
    }
}

public class SetPet
{
    public static void Main()
    {
        Pet obj = new Pet();
        obj.SetName("Aomsin");
        
        obj.DisplayPetInfo();
    }
}

OUTPUT

Pet's Name: Aomsin
Hello! I am Aomsin

อธิบาย code

จาก code ด้านบนมีการเรียกใช้ Method Hello โดยใช้this.ตามฟิลด์ name เพื่อเรียกใช้เมธอดในคลาส Pet

4.การใช้คีย์เวิร์ด this เป็นพารามิเตอร์ในMethod

Example

using System;

class Pet {
    public string name;

    public Pet(string name)
    {
        this.name = name;
    }

    public void DisplayPetName()
    {
        Console.WriteLine("Pet name: " + this.name);
    }

    public void PrintPetDetails(Pet pet)
    {
        Console.WriteLine("Pet name from another method: " + pet.name);
    }

    public void ShowDetails()
    {
        this.PrintPetDetails(this);
    }
}

class Program {
    public static void Main()
    {
        Pet myPet = new Pet("Aomsin");

        myPet.ShowDetails(); 
    }
}

OUTPUT

Pet name from another method: Aomsin

อธิบาย code

ในเมธอด showdetail มีการเรียก method PrintPetDetails ในคลาส Pet และส่งคลาส Pet เป็นพารามิเตอร์ให้ method PrintPetDetail เพื่อที่จะใช้ตัวแปร Name ของคลาส Pet

5. การใช้ this เพื่อประกาศ Indexer

Example

using System;
using System.Collections.Generic;

class Pet {
    private List<string> petNames = new List<string>();

    public string this[int index]
    {
        get
        {
            if (index >= 0 && index < petNames.Count)
            {
                return petNames[index];
            }
            else
            {
                return "Index out of range";
            }
        }
        set
        {
            if (index >= 0 && index < petNames.Count)
            {
                petNames[index] = value;
            }
            else if (index == petNames.Count)
            {
                petNames.Add(value);
            }
        }
    }

    public void AddPet(string name)
    {
        petNames.Add(name);
    }
}

class SetPet { 
    public static void Main()
    {
        Pet obj = new Pet();
        obj.AddPet("Aomsin");
        obj.AddPet("Dollar");
        
        Console.WriteLine("Pet at index 0: " + obj[0]);
        Console.WriteLine("Pet at index 1: " + obj[1]);

        obj[1] = "Gold";
        Console.WriteLine("Updated Pet at index 1: " + obj[1]);

        obj[2] = "Silver";
        Console.WriteLine("Pet at index 2: " + obj[2]);
    }
}

OUTPUT

Pet at index 0: Aomsin
Pet at index 1: Dollar
Updated Pet at index 1: Gold
Pet at index 2: Silver

คำอธิบาย code

Index declaration ประกอบด้วย get และ set ใน get เลขที่รับมามากกว่าเท่ากับ 0 และ เลขที่รับมามีข้อมูลในตำแหน่งนั้นจะทำการแสดงชื่อสัตว์เลี้ยงออกมา แต่ถ้าเลขที่รับมไม่มีข้อมูลในตำแหน่งนั้นจะไม่แสมาข้อความว่า Index out of range ส่วน set เลขที่รับมามากกว่าเท่ากับ 0 และ เลขที่รับมามีข้อมูลในตำแหน่งนั้นจะทำการเปลี่ยนค่าในตำแหน่งนั้นแทนหากเลขที่รับมาเกินจำนวนข้อมูลจะเป็นการเพิ่มข้ใมูลเข้าใน Array

ตัวอย่างการ Code ที่ใช้ this keyword

using System;

class Pet
{
    private string name;
    private string breed;
    private decimal price;

    public Pet(string name, string breed) : this(name, breed, 0.0m)
    {
        // Calls the three-parameter constructor
    }

    public Pet(string name, string breed, decimal price)
    {
        this.name = name;
        this.breed = breed;
        this.price = price;
    }

    public string Name
    {
        get { return this.name; }
    }

    public string Breed
    {
        get { return this.breed; }
    }

    public decimal Price
    {
        get { return this.price; }
        set { this.price = value; }
    }

    public string this[int index]
    {
        get
        {
            if (index == 0) return this.name;
            if (index == 1) return this.breed;
            return "Invalid index";
        }
        set
        {
            if (index == 0) this.name = value;
            if (index == 1) this.breed = value;
        }
    }

    public void PrintPetInfo()
    {
        Console.WriteLine("Pet Name: {0}\nBreed: {1}\nPrice: {2:C}", this.name, this.breed, this.price);
    }

    public void ChangePrice(decimal newPrice)
    {
        this.price = newPrice;
        this.PrintPriceUpdate();
    }

    private void PrintPriceUpdate()
    {
        Console.WriteLine("The price has been updated to {0:C}", this.price);
    }
}

class MainClass
{
    static void Main()
    {
        Pet pet1 = new Pet("Bella", "Golden Retriever", 12000.00m);
        Pet pet2 = new Pet("Milo", "Siamese Cat");

        pet1.PrintPetInfo();
        Console.WriteLine();
        pet2.PrintPetInfo();
        Console.WriteLine();

        pet1.ChangePrice(13000.00m);

        pet2[0] = "Luna";
        pet2[1] = "Persian Cat";
        Console.WriteLine("\nUpdated pet2 info using indexer:");
        pet2.PrintPetInfo();
    }
}

OUTPUT

Pet Name: Bella
Breed: Golden Retriever
Price: ฿12,000.00

Pet Name: Milo
Breed: Siamese Cat
Price: ฿0.00

The price has been updated to ฿13,000.00
Pet Name: Bella
Breed: Golden Retriever
Price: ฿13,000.00

Updated pet2 info using indexer:
Pet Name: Luna
Breed: Persian Cat
Price: ฿0.0

คำอธิบาย

คลาส Pet ประกอบด้วยชื่อสัตว์เลี้ยง(name) สายพันธุ์(breed) และราคา(price) คลาสPetมี constructor 2 แบบ แบบแรกจะมีการกำหนดราคา(price) เป็น 0 โดยอัตโนมัติ แบบที่สองจะรับราคา(price)มาจากเราสามารถกำหนดเองได้ และมี property หรือ ตัวกลางของ name,breed,price โดย property ของ price สามารถเปลี่ยนได้ด้วยโครงสร้าง set ของ property ต่อมามีการใช้ this เพื่อประกาศ Indexer ทำให้สามารถเข้าถึงและ upload ข้อมูลได้ตามเลข index ในส่วนของ method ChangePrice มีการใช้ this เพื่อเข้าถึง instance ของคลาสปัจจุบัน และ ใช้ this เพื่อเรียก method ภายในคลาสเดียวกัน

นำมาเขียนด้วยภาษา C

#include <stdio.h>
#include <string.h>

typedef struct {
    char name[50];
    char breed[50];
    float price;
} Pet;

// ฟังก์ชันที่จำลองการเข้าถึงข้อมูลใน struct โดยการส่ง pointer
void printPetInfo(Pet *pet) {
    printf("Pet Name: %s\n", pet->name);
    printf("Breed: %s\n", pet->breed);
    printf("Price: %.2f\n", pet->price);
}

// ฟังก์ชันที่จำลองการเปลี่ยนแปลงข้อมูลใน struct
void changePrice(Pet *pet, float newPrice) {
    pet->price = newPrice;
}

int main() {
    Pet pet1;
    strcpy(pet1.name, "Bella");
    strcpy(pet1.breed, "Golden Retriever");
    pet1.price = 12000.00;

    printPetInfo(&pet1);

    changePrice(&pet1, 13000.00);
    printf("\nUpdated Pet Info:\n");
    printPetInfo(&pet1);

    return 0;
}

ความแตกต่างระหว่างภาษา C และภาษา C#

• ในภาษา C ใช้ struct ในการเก็บข้อมูลเกี่ยวกับสัตว์เลี้ยง เช่น name, breed, และ price แทนการใช้ class

• ในภาษา C ใช้ pointer (Pet *pet) เพื่อจำลองการเข้าถึงข้อมูลใน struct แทนการใช้ this ใน C# โดยใช้ -> เพื่อเข้าถึงสมาชิกในโครงสร้าง (คล้ายกับการใช้ this เพื่อเข้าถึงสมาชิกของออบเจ็กต์ใน C#)

• ในภาษา C ฟังก์ชัน changePrice ใช้ pointer เพื่อเปลี่ยนแปลงค่าภายในโครงสร้างโดยตรง

สรุป

ใน C ต้องจัดการข้อมูลผ่านการใช้ pointer และ struct ไม่มี this แบบภาษาC#

นำมาเขียนด้วยภาษา Java

public class Pet {
    private String name;
    private String breed;
    private double price;

    // Constructor ที่ใช้ this เพื่อแยกพารามิเตอร์กับตัวแปรภายในออบเจ็กต์
    public Pet(String name, String breed) {
        this(name, breed, 0.0); // เรียก constructor ที่มี 3 พารามิเตอร์
    }

    // Constructor 3 พารามิเตอร์
    public Pet(String name, String breed, double price) {
        this.name = name;   
        this.breed = breed; 
        this.price = price;
    }

    // Method เพื่อแสดงข้อมูลของสัตว์เลี้ยง
    public void printPetInfo() {
        System.out.println("Pet Name: " + this.name);
        System.out.println("Breed: " + this.breed);
        System.out.println("Price: " + this.price);
    }

    // Method เพื่อเปลี่ยนราคาและเรียกใช้ method อื่น
    public void updatePrice(double newPrice) {
        this.price = newPrice;    
        this.printPetInfo();      
    }

    // Method เพื่อส่งออบเจ็กต์ปัจจุบัน (this) ไป method อื่น
    public void passObject(Pet anotherPet) {
        anotherPet.printPetInfo(); 
    }

    public static void main(String[] args) {
        Pet pet1 = new Pet("Bella", "Golden Retriever", 12000.00);
        Pet pet2 = new Pet("Milo", "Siamese Cat");

        pet1.printPetInfo();
        System.out.println();
        pet2.printPetInfo();

        System.out.println("\nUpdating pet1 price:");
        pet1.updatePrice(13000.00);

        System.out.println("\nPassing pet1 object:");
        pet1.passObject(pet1);

        System.out.println("\nUpdating pet2 info:");
        pet2.name = "Luna"; 
        pet2.breed = "Persian Cat";
        pet2.printPetInfo();
    }
}

ความแตกต่างระหว่าง Java และ C#

ทั้งสองภาษามีการใช้ this ตามสถานการณ์ต่างๆที่เหมือนกันแต่ต่างกันที่ใน C# มี property ช่วยในการเข้าถึงตัวแปรภายในโดยมี getter และ setterแต่ใน Java ไม่มี property syntax การใช้ this กับ getter และ setter ใน Java จึงต้องเรียกใช้ method โดยตรง

ตัวอย่างเปรียบเทียบ Property ใน C# กับ Java (เพิ่มเติมจาก code ด้านบน)

Code ProperTy Syntax In C#

public class Pet {
    private string name;

    public string Name {
        get { return this.name; }
        set { this.name = value; }
    }
}

Code In Java

public class Pet {
    private String name;

    public String getName() {
        return this.name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

นำมาเขียนด้วย Python

class Pet:
    def __init__(self, name, breed, price=0.0):
        self.name = name    # ใช้ self เพื่อเข้าถึงตัวแปรภายใน object
        self.breed = breed
        self.price = price

    def print_pet_info(self):
        print(f"Pet Name: {self.name}")
        print(f"Breed: {self.breed}")
        print(f"Price: {self.price}")

    def update_price(self, new_price):
        self.price = new_price
        self.print_pet_info()  # เรียก method ภายใน object เดียวกัน

# สร้างออบเจ็กต์และเรียกใช้ method
pet1 = Pet("Bella", "Golden Retriever", 12000.00)
pet2 = Pet("Milo", "Siamese Cat")

pet1.print_pet_info()
pet2.print_pet_info()

print("\nUpdating pet1 price:")
pet1.update_price(13000.00)

ความต่างระหว่าง C# กับ Python

• ใน C# ใช้คำว่า this เพื่ออ้างถึงออบเจ็กต์ปัจจุบันของ class ส่วนใน python ใช้คำว่า self เพื่ออ้างถึงออบเจ็กต์ปัจจุบันของ class

• Python ต้องใส่ self เป็นพารามิเตอร์แรกของทุก method เสมอเพื่อให้เข้าใจว่า method นั้นทำงานกับ object อะไร

• constructor ใช้ method init() เป็น constructor และไม่สามารถเรียก constructor อื่นโดยตรงผ่าน self ได้ต้องใช้ แต่ในภาษา C# สามารถเรียกผ่าน this ได้

• Python ไม่มี property แบบ C# แต่สามารถใช้ decorator @property เพื่อสร้าง getter และ setterได้

class Pet:
    def __init__(self, name):
        self._name = name

    @property
    def name(self):
        return self._name

    @name.setter
    def name(self, value):
        self._name = value

Reference

Last updated