Constructor sao chép tạo đối tượng bằng cách sao chép biến từ đối tượng khác.
Ví dụ
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();
}
}
}
Quy trình: khai báo copy constructor public Student(Student s), tạo đối tượng s1, sau đó sao chép s1 sang s2 mới.