C#復(fù)制構(gòu)造函數(shù)的實(shí)質(zhì)淺析
我們在討論C#復(fù)制構(gòu)造函數(shù)之前想要明白什么是復(fù)制構(gòu)造函數(shù)?
我們知道構(gòu)造函數(shù)是用來初始化我們要創(chuàng)建實(shí)例的特殊的方法。通常我們要將一個實(shí)例賦值給另外一個變量c#只是將引用賦值給了新的變量實(shí)質(zhì)上是對同一個變量的引用,那么我們怎樣才可以賦值的同時創(chuàng)建一個全新的變量而不只是對實(shí)例引用的賦值呢?我們可以使用復(fù)制構(gòu)造函數(shù)。
我們可以為類創(chuàng)造一個只用一個類型為該類型的參數(shù)的構(gòu)造函數(shù),如:
- public Student(Student student)
- {
- this.name = student.name;
- }
C#復(fù)制構(gòu)造函數(shù)的實(shí)質(zhì):使用上面的構(gòu)造函數(shù)我們就可以復(fù)制一份新的實(shí)例值,而非賦值同一引用的實(shí)例了。
- class Student
- {
- private string name;
- public Student(string name)
- {
- this.name = name;
- }
- public Student(Student student)
- {
- this.name = student.name;
- }
- public string Name
- {
- get
- {
- return name;
- }
- set
- {
- name = value;
- }
- }
- }
- class Final
- {
- static void Main()
- {
- Student student = new Student ("A");
- Student NewStudent = new Student (student);
- student.Name = "B";
- System.Console.WriteLine(
- "The new student's name is {0}",
- NewStudent.Name);
- }
- }
C#復(fù)制構(gòu)造函數(shù)的應(yīng)用的一點(diǎn)體會就向你介紹到這里,希望對你理解和學(xué)習(xí)C#復(fù)制構(gòu)造函數(shù)有所幫助。
【編輯推薦】