C#复制构造函数

我们知道构造函数是用来初始化我们要创建实例的特殊的方法。通常我们要将一个实例赋值给另外一个变量c#只是将引用赋值给了新的变量实质上是对同一个变量的引用,那么我们怎样才可以赋值的同时创建一个全新的变量而不只是对实例引用的赋值呢?我们可以使用复制构造函数。

我们可以为类创造一个只用一个类型为该类型的参数的构造函数,如:

 
 
  1. public Student(Student student)  
  2. {  
  3.  this.name = student.name;  

C#复制构造函数的实质:使用上面的构造函数我们就可以复制一份新的实例值,而非赋值同一引用的实例了。

 
 
  1. class Student  
  2. {  
  3.  private string name;  
  4.  
  5.  public Student(string name)  
  6.   {  
  7.  this.name = name;  
  8.  }  
  9.  public Student(Student student)  
  10.   {  
  11.  this.name = student.name;  
  12.  }  
  13.  
  14. public string Name   
  15.  {  
  16.    get   
  17. {  
  18.   return name;   
  19.    }  
  20.    set   
  21. {  
  22. name = value;   
  23.    }  
  24. }  
  25. }  
  26.  
  27. class Final  
  28.  
  29. {  
  30.  
  31. static void Main()  
  32.  
  33.    {  
  34.  
  35. Student student = new Student ("A");  
  36.  
  37. Student NewStudent = new Student (student);  
  38.  
  39. student.Name = "B";  
  40.  
  41. System.Console.WriteLine(  
  42. "The new student's name is {0}",  
  43.  NewStudent.Name);  
  44.  
  45.   }  
  46.  
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值