更新:2007 年 11 月
与有些语言不同,C# 不提供复制构造函数。如果您创建了新的对象并希望从现有对象复制值,您必须自行编写适当的方法。
示例
在本示例中,Person
C# | 复制代码 |
---|---|
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 |