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

这就是我们所说的拷贝构造函数。

更新时间:2020 年 6 月 21 日

3K+ 浏览量

启动您的职业生涯

通过完成课程获得认证

开始学习
广告
© . All rights reserved.