HOW TO:撰寫複製建構函式 (C# 程式設計手冊)
與某些語言不同的是,C# 不會提供複製建構函式。 如果您建立了新物件,而且想要從現有物件複製值,就必須自行撰寫適當的方法。
範例
在此範例中,Person class 包含的建構函式會將 Person 型別的其他物件當做引數。 這個物件的欄位內容便會指派給新物件的欄位。 替代複製建構函式將待複製物件的 name 和 age 欄位傳送至類別的執行個體建構函式。
class Person
{
private string name;
private int age;
// Copy constructor.
public Person(Person previousPerson)
{
name = previousPerson.name;
age = previousPerson.age;
}
//// Alternate copy contructor calls the instance constructor.
//public Person(Person previousPerson)
// : this(previousPerson.name, 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 person1.
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