什么是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显示 {
get {
return " Student " + name +" got Rank "+ rank.ToString();
}
}
}
class StudentInfo {
static void Main() {
Student s1 = new Student("Jack", 2);
//复制构造函数
Student s2 = new Student(s1);
//显示
Console.WriteLine(s2.Display);
Console.ReadLine();
}
}
}在上面我们看到,首先我们声明了一个拷贝构造函数-
public Student(Student s)
然后为Student类创建一个新对象-
Student s1 = new Student("Jack", 2);现在,将s1对象复制到新对象s2-
Student s2 = new Student(s1);
这就是我们所谓的复制构造函数。
热门推荐
1 训练狗狗基础
2 怎么训练狗狗笑
3 怎么训练狗狗卧下
4 上海狗狗训练基地
5 训练狗狗排便
6 狗狗基础训练
8 如何训练狗狗装死
9 狗狗站姿训练
10 狗狗训练用品
11 训练狗狗吧
12 狗狗要怎么训练
13 怎么训练狗狗玩球
14 训练狗狗唤回
15 狗狗训练躺下
16 狗狗训练指令
17 狗狗的训练技巧
18 狗狗不好训练