Copy Constructor สร้างวัตถุโดยการคัดลอกตัวแปรจากวัตถุอื่น
เรามาดูตัวอย่างกัน −
ตัวอย่าง
using System;
namespace Demo {
class Student {
private string name;
private int rank;
public Student(Student s) {
name = s.name;
rank = s.rank;
}
public Student(string name, int rank) {
this.name = name;
this.rank = rank;
}
public string Display {
get {
return " Student " + name +" got Rank "+ rank.ToString();
}
}
}
class StudentInfo {
static void Main() {
Student s1 = new Student("Jack", 2);
// copy constructor
Student s2 = new Student(s1);
// display
Console.WriteLine(s2.Display);
Console.ReadLine();
}
}
} ด้านบนเราเห็น ประการแรก เราประกาศตัวสร้างการคัดลอก -
public Student(Student s)
จากนั้นจึงสร้างวัตถุใหม่สำหรับชั้นเรียนนักเรียน -
Student s1 = new Student("Jack", 2); ตอนนี้ วัตถุ s1 ถูกคัดลอกไปยังวัตถุใหม่ s2 -
Student s2 = new Student(s1);
นี่คือสิ่งที่เราเรียกว่าตัวสร้างการคัดลอก