다음을 통해 공유


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

C#는 개체에 대한 복사 생성자를 제공하지 않지만 사용자가 직접 작성할 수 있습니다.

예제

다음 예에서 Person 클래스는 해당 인수로 Person 인스턴스를 받아들이는 복사 생성자를 정의합니다. 인수의 속성 값은 Person의 새 인스턴스 속성에 할당됩니다. 코드는 클래스의 인스턴스 생성자에게 복사하려는 Name 및 Age 인스턴스 속성을 보내는 다른 복사 생성자를 포함합니다.

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

참고 항목

참조

클래스 및 구조체(C# 프로그래밍 가이드)

생성자(C# 프로그래밍 가이드)

소멸자(C# 프로그래밍 가이드)

ICloneable

개념

C# 프로그래밍 가이드