什么是 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