다음을 통해 공유


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

업데이트: 2007년 11월

일부 언어와는 달리 C#에서는 복사 생성자를 제공하지 않습니다. 새 개체를 만들고 기존 개체에서 값을 복사하려면 적절한 메서드를 직접 작성해야 합니다.

예제

이 예제에서 Person클래스에는 Person 형식의 다른 개체를 인수로 받는 생성자가 있습니다. 이 생성자에서는 다른 개체의 필드 내용을 새 개체의 필드에 할당합니다.

class Person
{
    private string name;
    private int age;

    // Copy constructor.
    public Person(Person previousPerson)
    {
        name = previousPerson.name;
        age = previousPerson.age;
    }

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

    // Get accessor.
    public string Details
    {
        get
        {
            return name + " is " + age.ToString();
        }
    }
}

class TestPerson
{
    static void Main()
    {
        // Create a new person object.
        Person person1 = new Person("George", 40);

        // Create another new object, copying person.
        Person person2 = new Person(person1);
        Console.WriteLine(person2.Details);

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

참고 항목

개념

C# 프로그래밍 가이드

참조

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

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

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

ICloneable