コピー コンストラクターを記述する方法 (C# プログラミング ガイド)

オブジェクトには C# レコードによってコピー コンストラクターが提供されますが、クラスには自分でそれを記述する必要があります。

重要

クラス階層内のすべての派生型に対して機能するコピー コンストラクターを記述するのは難しい場合があります。 クラスが sealed でない場合は、コンパイラによって合成されたコピー コンストラクターを使う record class 型の階層を作ることを検討することを強くお勧めします。

例

次の例の Person クラスでは、Person のインスタンスを引数として受け取るコピー コンストラクターが定義されています。 引数のプロパティの値は、Personの新しいインスタンスのプロパティに割り当てられています。 このコードには、コピーするインスタンスの Name プロパティと Age プロパティをクラスのインスタンス コンストラクターに渡す代替のコピー コンストラクターが含まれています。 Person クラスは sealed なので、基底クラスのみをコピーしてエラーを引き起こすような派生型は宣言できません。

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

関連項目