Constructors in C#
ภูริณัฐ วงษ์นาคเพ็ชร์ 650710576
Constructor คืออะไร?
Constructor คือเมธอดพิเศษในคลาสของภาษาโปรแกรม ที่ทำงานเมื่อมีการสร้างอินสแตนซ์ของคลาสนั้นๆ ขึ้นมา ภาษา C# จะใช้ Constructor เพื่อตั้งเป็นค่าเริ่มต้นของออบเจ็คต์ ซึ่งรวมถึงการกำหนดค่าของตัวแปรในคลาสหรือการทำบางสิ่งก่อนการใช้งาน
KEY POINT CONSTRUCTOR C#
constructor ของคลาสจะต้องเป็นชื่อเดียวกับชื่อคลาสที่เราสร้าง
constructor ไม่มีการคืนค่าชนิดใดๆ รวมถึง void
คลาสทุกคลาสที่เราสร้างขึ้นมาจะต้องมี constructor อย่างน้อย 1 ตัวเสมอ
คลาสหนึ่งสามารถมี constructor จำนวนเท่าใดก็ได้
ภายในคลาส สามารถสร้าง constructor แบบคงที่ได้เพียงตัวเดียวเท่านั้น
static constructor ไม่สามารถรับพารามิเตอร์ได้
Types of Constructors
Default Constructor
Parameterized Constructor
Copy Constructor
Private Constructor
Static Constructor
Example
class Person {
String name;
int age;
// Constructor
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public static void main(String[] args) {
Person person = new Person("Alice", 30);
System.out.println("Name: " + person.name + ", Age: " + person.age);
}
}
จากตัวอย่าง บรรทัดที่ 6-9 จะเป็นการสร้าง Constructor คลาส Person มี Constructor ที่ใช้กำหนดค่าเริ่มต้นให้กับคุณสมบัติ Name และ Age เมื่อมีการสร้างอ็อบเจกต์ขึ้นมาเเละไม่มีการคืนค่า
การเรียกใช้ Constructor
เมื่อทำการสร้างอินสแตนซ์ของ Person โดยการใช้
Person person = new Person("Alice", 30);
Constructor จะถูกเรียกใช้ และค่าที่ถูกส่งเข้าไป (Alice", 30) จะถูกตั้งค่าให้กับตัวแปร Name และ Age ตามลำดับ
เปรียบเทียบ Constructor ใน C#/Java /C/Python
class Car
{
public string model;
public string color;
public int year;
// Constructor
public Car(string modelName, string modelColor, int modelYear)
{
model = modelName;
color = modelColor;
year = modelYear;
}
static void Main(string[] args)
{
Car Ford = new Car("Mustang", "Red", 1969);
Console.WriteLine(Ford.color + " " + Ford.year + " " + Ford.model);
}
}
struct Car createCar(char* modelName, char* modelColor, int modelYear) {
struct Car car;
strcpy(car.model, modelName);
strcpy(car.color, modelColor);
car.year = modelYear;
return car;
}
def __init__(self, model, color, year):
self.model = model
self.color = color
self.year = year
Video Presentation
Slide Presentation
Reference
ข้อมูลและการทำงานของ constructor in c#
เปรียบเทียบตัวอย่างโค้ด
Last updated