什麼是 C# 中的複製建構函式?
複製建構函式透過從其他物件中複製變數來建立物件。
讓我們看一個示例 −
示例
using System;
namespace Demo {
class Student {
private string name;
private int rank;
public Student(Student s) {
name = s.name;
rank = s.rank;
}
public Student(string name, int rank) {
this.name = name;
this.rank = rank;
}
public string Display {
get {
return " Student " + name +" got Rank "+ rank.ToString();
}
}
}
class StudentInfo {
static void Main() {
Student s1 = new Student("Jack", 2);
// copy constructor
Student s2 = new Student(s1);
// display
Console.WriteLine(s2.Display);
Console.ReadLine();
}
}
}上面我們看到,我們首先聲明瞭一個複製建構函式 −
public Student(Student s)
然後,為 Student 類建立了一個新的物件 −
Student s1 = new Student("Jack", 2);現在,s1 物件被複制到一個新的物件 s2 −
Student s2 = new Student(s1);
這就是我們所說的複製建構函式。
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP