Languages
[Edit]
PL

C# - konstruktor kopiujący

4 points
Created by:
Creg
9600

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
    }
}

 

Zobacz także

  1. C# - czym jest konstruktor w programowaniu obiektowym?

  2. C# - konstruktor domyślny

Referencje

  1. Składnia konstruktora - Konstruktory (Przewodnik programowania w języku C#)
  2. Jak napisać konstruktor kopii (Przewodnik programowania w języku C#)

Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join