PL
C# - konstruktor kopiujący
4
points
W języku C#, programując obiektowo mamy możliwość tworzenia konstruktorów kopiujących. Konstruktor kopiujący to taki, który tworzy kopię obiektu, przyjmując jeden argument tego samego typu co klasa, w której się znajduje (czyli kopiowany obiekt).
Szybkie rozwiązanie:
public class ClassName
{
private string field;
// inne konstruktory tutaj ...
public ClassName(ClassName someObject) // <-- konstruktor kopiujący: przyjmuje on obiekt tego samego typu co klasa, w której się znajduje
{
this.field = someObject.field;
}
}
Praktyczne przykłady
1. Przykład 1
public class Program
{
public static void Main()
{
Student student = new Student("Jan");
Student kopia1 = new Student(student); // <-- wywoływanie konstruktora kopiującego
Student kopia2 = new Student(student); // <-- wywoływanie konstruktora kopiującego
// ciąg dalszy programu ...
}
}
public class Student
{
private string name;
public Student(string name)
{
this.name = name;
}
public Student(Student student) // <-- tworzenie konstruktora kopiującego
{
this.name = student.name; // <-- przepisanie pól (w naszym przypadku przepisujemy tylko name)
}
}
2. Przykład 2
public class Program
{
public static void Main()
{
Student student = new Student("Jan", 25);
Student kopia1 = new Student(student); // <-- wywoływanie konstruktora kopiującego
Student kopia2 = new Student(student); // <-- wywoływanie konstruktora kopiującego
// ciąg dalszy programu ...
}
}
public class Student
{
private string name;
private int age;
public Student(string name, int age)
{
this.name = name;
this.age = age;
}
public Student(Student student) // <-- tworzenie konstruktora kopiującego
{
this.name = student.name; // <-- przepisanie pola name
this.age = student.age; // <-- przepisanie pola age
}
}