C#復(fù)制構(gòu)造函數(shù)的編寫淺析
C#復(fù)制構(gòu)造函數(shù)在C#中是如何編寫的呢?
與有些語言不同,C#復(fù)制構(gòu)造函數(shù)在C#是不提供。如果您創(chuàng)建了新的對象并希望從現(xiàn)有對象復(fù)制值,您必須自行編寫適當(dāng)?shù)姆椒ā?/P>
在本示例中,Person 類包含一個構(gòu)造函數(shù),該構(gòu)造函數(shù)接受另一個 Person 類型的對象作為參數(shù)。然后此對象的字段中的內(nèi)容將分配給新對象中的字段。
C#復(fù)制構(gòu)造函數(shù)的編寫代碼:
- 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 person1.
- Person person2 = new Person(person1);
- System.Console.WriteLine(person2.Details);
- }
- }
C#復(fù)制構(gòu)造函數(shù)代碼輸出:
- George is 40
C#復(fù)制構(gòu)造函數(shù)的編寫過程就向你簡單介紹到這里,希望對你學(xué)習(xí)和理解C#復(fù)制構(gòu)造函數(shù)有所幫助。
【編輯推薦】