복사 생성자를 작성하는 방법(C# 프로그래밍 가이드)

C# 레코드는 개체의 복사 생성자를 제공하지만 클래스의 경우 직접 작성해야 합니다.

중요

클래스 계층 구조의 모든 파생 형식에 대해 작동하는 복사 생성자를 작성하는 것은 어려울 수 있습니다. 클래스가 이 아닌 sealed경우 컴파일러 합성 복사 생성자를 사용하도록 형식의 record class 계층 구조를 만드는 것이 좋습니다.

예제

다음 예제에서 Person클래스Person 인스턴스를 해당 인수로 사용하는 복사 생성자를 정의합니다. 인수의 속성 값이 Person의 새 인스턴스 속성에 할당됩니다. 코드에는 복사하려는 인스턴스의 NameAge 속성을 클래스의 인스턴스 생성자에 보내는 대체 복사 생성자가 포함되어 있습니다. 클래스는 Personsealed이므로 기본 클래스만 복사하여 오류를 발생시킬 수 있는 파생 형식을 선언할 수 없습니다.

public sealed class Person
{
    // Copy constructor.
    public Person(Person previousPerson)
    {
        Name = previousPerson.Name;
        Age = previousPerson.Age;
    }

    //// Alternate copy constructor calls the instance constructor.
    //public Person(Person previousPerson)
    //    : this(previousPerson.Name, previousPerson.Age)
    //{
    //}

    // Instance constructor.
    public Person(string name, int age)
    {
        Name = name;
        Age = age;
    }

    public int Age { get; set; }

    public string Name { get; set; }

    public string Details()
    {
        return Name + " is " + Age.ToString();
    }
}

class TestPerson
{
    static void Main()
    {
        // Create a Person object by using the instance constructor.
        Person person1 = new Person("George", 40);

        // Create another Person object, copying person1.
        Person person2 = new Person(person1);

        // Change each person's age.
        person1.Age = 39;
        person2.Age = 41;

        // Change person2's name.
        person2.Name = "Charles";

        // Show details to verify that the name and age fields are distinct.
        Console.WriteLine(person1.Details());
        Console.WriteLine(person2.Details());

        // Keep the console window open in debug mode.
        Console.WriteLine("Press any key to exit.");
        Console.ReadKey();
    }
}
// Output:
// George is 39
// Charles is 41

참고 항목