博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
深拷贝与浅拷贝
阅读量:7098 次
发布时间:2019-06-28

本文共 1921 字,大约阅读时间需要 6 分钟。

浅拷贝

浅拷贝是字段的被拷贝,而字段的引用的对象不会被拷贝,拷贝对象和源对象仅仅是引用名称有所不同,他们公用一份实体,改变其中一个都会影响到因为一个对象。

void Main(){     Student s1=new Student("objectboy",27);    Student s2=s1;    s2.Age=20;    s1.ShowInfo();    s1.Age=11;    s2.ShowInfo();}public class Student{    public string Name;    public int Age;    public Student(string name,int age){        Name=name;        Age=age;    }    public void ShowInfo(){        Console.WriteLine("{0}'s age is {1} ",Name,Age);    }}
输出:objectboy's age is 20 objectboy's age is 11

 深拷贝

对象的字段拷贝,同时对象的引用也被拷贝,不共用一个对象,改变其中一个对象不会影响到另外一个对象(一般值类型的拷贝就是深拷贝)。

void Main(){    int i=0;    int j=i;    i=2;    Console.WriteLine(i);    Console.WriteLine(j);}
输出:20

 浅拷贝实现

void Main(){    var sourceEnrollment=new Enrollment();    sourceEnrollment.students.Add(new Student(){Name="objectboy",Age=27});    sourceEnrollment.students.Add(new Student(){Name="hky",Age=27});        Enrollment cloneStudents=sourceEnrollment.Clone() as Enrollment;  //克隆    sourceEnrollment.ShowEnrollmentInfo();    cloneStudents.ShowEnrollmentInfo();        Console.WriteLine("------------------------------");        cloneStudents.students[0].Name="boyobject";    cloneStudents.students[0].Age=22;    sourceEnrollment.ShowEnrollmentInfo();    cloneStudents.ShowEnrollmentInfo();}class Enrollment:ICloneable{    public  List
students=new List
(); public void ShowEnrollmentInfo(){ foreach (var element in students) { Console.WriteLine("{0}'s age is {1}",element.Name,element.Age); } } public object Clone(){ return MemberwiseClone(); }}public class Student{ public string Name{
get;set;} public int Age{
get;set;}}
输出:objectboy's age is 27hky's age is 27objectboy's age is 27hky's age is 27------------------------------boyobject's age is 22hky's age is 27boyobject's age is 22hky's age is 27

 

转载于:https://www.cnblogs.com/objectboy/p/4623231.html

你可能感兴趣的文章
UED
查看>>
Hello World 之 控制台版本(Console Application)
查看>>
linux下nginx+php+mysql 自助环境搭建
查看>>
udp通信
查看>>
国家模式c++
查看>>
假设动态运行java文字,当在脚本式配置,这是非常方便的
查看>>
android4.0 的图库Gallery2代码分析(三) 之Applition的初始化准备
查看>>
SOM自组织映射网络 教程
查看>>
lintcode:寻找旋转排序数组中的最小值 II
查看>>
树莓派学习笔记——交叉编译练习之SQLite3安装
查看>>
android stuido build 慢的解决办法
查看>>
Appium移动自动化测试(四)--one demo
查看>>
nginx配置location总结及rewrite规则写法
查看>>
python 登陆接口
查看>>
RedHat7 部署ELK日志分析系统
查看>>
DS实验题 Missile
查看>>
微信上 网页图片点击全屏放大
查看>>
jquery获取css颜色值返回RGB应用
查看>>
(void __user *)arg 中__user的作用
查看>>
Redefine:Change in the Changing World
查看>>