如何撰寫複製建構函式 (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