คีย์เวิร์ด “this” ใน C# ใช้เพื่ออ้างถึงอินสแตนซ์ปัจจุบันของคลาส นอกจากนี้ยังใช้เพื่อแยกความแตกต่างระหว่างพารามิเตอร์ของเมธอดและฟิลด์คลาส หากทั้งคู่มีชื่อเหมือนกัน
การใช้คีย์เวิร์ด “นี้” อีกประการหนึ่งคือการเรียกคอนสตรัคเตอร์อื่นจากคอนสตรัคเตอร์ในคลาสเดียวกัน
ตัวอย่างเช่น เรากำลังแสดงบันทึกของนักเรียน เช่น รหัส ชื่อ อายุ และหัวเรื่อง เพื่ออ้างถึงฟิลด์ของคลาสปัจจุบัน เราได้ใช้คีย์เวิร์ด “this” ใน C# −
public Student(int id, String name, int age, String subject) {
this.id = id;
this.name = name;
this.subject = subject;
this.age = age;
} ตัวอย่าง
ให้เราดูตัวอย่างที่สมบูรณ์เพื่อเรียนรู้วิธีการทำงานกับคำหลัก "นี้" ใน C# -
using System.IO;
using System;
class Student {
public int id, age;
public String name, subject;
public Student(int id, String name, int age, String subject) {
this.id = id;
this.name = name;
this.subject = subject;
this.age = age;
}
public void showInfo() {
Console.WriteLine(id + " " + name+" "+age+ " "+subject);
}
}
class StudentDetails {
public static void Main(string[] args) {
Student std1 = new Student(001, "Jack", 23, "Maths");
Student std2 = new Student(002, "Harry", 27, "Science");
Student std3 = new Student(003, "Steve", 23, "Programming");
Student std4 = new Student(004, "David", 27, "English");
std1.showInfo();
std2.showInfo();
std3.showInfo();
std4.showInfo();
}
}