ตัวสร้าง
ตัวสร้างคลาสเป็นฟังก์ชันสมาชิกพิเศษของคลาสที่ดำเนินการทุกครั้งที่เราสร้างวัตถุใหม่ของคลาสนั้น
คอนสตรัคเตอร์มีชื่อเหมือนกันทุกประการกับชื่อคลาส และไม่มีประเภทการส่งคืน
ตัวสร้างมีชื่อเดียวกับชื่อคลาส -
class Demo {
public Demo() {}
} ต่อไปนี้เป็นตัวอย่าง −
ตัวอย่าง
using System;
namespace LineApplication {
class Line {
private double length; // Length of a line
public Line() {
Console.WriteLine("Object is being created");
}
public void setLength( double len ) {
length = len;
}
public double getLength() {
return length;
}
static void Main(string[] args) {
Line line = new Line();
// set line length
line.setLength(6.0);
Console.WriteLine("Length of line : {0}", line.getLength());
Console.ReadKey();
}
}
} ผลลัพธ์
Object is being created Length of line : 6
ตัวทำลาย
destructor เป็นฟังก์ชันพิเศษของคลาสที่ดำเนินการเมื่อใดก็ตามที่วัตถุในคลาสนั้นอยู่นอกขอบเขต จะไม่สามารถคืนค่าหรือรับพารามิเตอร์ใดๆ ได้
มีชื่อเดียวกับชื่อคลาสที่มีเครื่องหมายตัวหนอน (~) นำหน้า เช่น ชื่อคลาสของเราคือ Demo −
public Demo() { // constructor
Console.WriteLine("Object is being created");
}
~Demo() { //destructor
Console.WriteLine("Object is being deleted");
} มาดูตัวอย่างการใช้งาน Destructors ใน C# กัน −
ตัวอย่าง
using System;
namespace LineApplication {
class Line {
private double length; // Length of a line
public Line() { // constructor
Console.WriteLine("Object is being created");
}
~Line() { //destructor
Console.WriteLine("Object is being deleted");
}
public void setLength( double len ) {
length = len;
}
public double getLength() {
return length;
}
static void Main(string[] args) {
Line line = new Line();
// set line length
line.setLength(6.0);
Console.WriteLine("Length of line : {0}", line.getLength());
}
}
} ผลลัพธ์
Object is being created Length of line : 6 Object is being deleted