C#復(fù)制構(gòu)造函數(shù)的實(shí)質(zhì)淺析
我們?cè)谟懻揅#復(fù)制構(gòu)造函數(shù)之前想要明白什么是復(fù)制構(gòu)造函數(shù)?
我們知道構(gòu)造函數(shù)是用來(lái)初始化我們要?jiǎng)?chuàng)建實(shí)例的特殊的方法。通常我們要將一個(gè)實(shí)例賦值給另外一個(gè)變量c#只是將引用賦值給了新的變量實(shí)質(zhì)上是對(duì)同一個(gè)變量的引用,那么我們?cè)鯓硬趴梢再x值的同時(shí)創(chuàng)建一個(gè)全新的變量而不只是對(duì)實(shí)例引用的賦值呢?我們可以使用復(fù)制構(gòu)造函數(shù)。
我們可以為類創(chuàng)造一個(gè)只用一個(gè)類型為該類型的參數(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)體會(huì)就向你介紹到這里,希望對(duì)你理解和學(xué)習(xí)C#復(fù)制構(gòu)造函數(shù)有所幫助。
【編輯推薦】