您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
浅拷贝和深拷贝主要体现在引用成员上.先上例子:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace CopyDemo
{
/// <summary>
/// 人类
/// </summary>
public sealed class Person
{
public string Name { set; get; }
public uint age { set; get; }
public Person partner { set; get; }
}
}对Person执行浅拷贝:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace CopyDemo
{
class Program
{
static void Main(string[] args)
{
Person i = new Person();
i.Name = "Aonaufly";
i.age = 27;
i.partner = new Person() { Name = "Kayer", age = 18 };
Person i_1 = i;
Console.WriteLine("我的name : {0} , copy的name : {1}", i.Name, i_1.Name);
Console.WriteLine("我的Partner的Name : {0} , copy的Partner的age : {1}", i.partner.Name, i_1.partner.Name);
Console.WriteLine("==========================================================");
i_1.partner.Name = "Ainy";
i_1.Name = "CC";
Console.WriteLine("我的name : {0} , copy的name : {1}", i.Name, i_1.Name);
Console.WriteLine("我的Partner的Name : {0} , copy的Partner的age : {1}", i.partner.Name, i_1.partner.Name);
Console.ReadLine();
}
}
}结果如下:

由于源对象和Copy对象的都指向同一块内存,互相直接的Update都会对另一个产生作用.
实际上 , 上述方案是不可取的.2对象都指向都一个地址,这不纯粹的浪费空间吗 ? 重点 : MemberwiseClone是C#用于实现浅拷贝的方案.
使用方法 :
①:继承 ICloneable
②:实现ICloneable的Clone方法
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace CopyDemo
{
/// <summary>
/// 人类
/// </summary>
public sealed class Person : ICloneable
{
public string Name { set; get; }
public uint age { set; get; }
public Person partner { set; get; }
//实现ICloneable接口
public object Clone()
{
return this.MemberwiseClone();
}
}
}调用:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace CopyDemo
{
class Program
{
static void Main(string[] args)
{
Person i = new Person();
i.Name = "Aonaufly";
i.age = 27;
i.partner = new Person() { Name = "Kayer", age = 18 };
Person i_1 = (Person)i.Clone();
Console.WriteLine("我的name : {0} , copy的name : {1}", i.Name, i_1.Name);
Console.WriteLine("我的Partner的Name : {0} , copy的Partner的age : {1}", i.partner.Name, i_1.partner.Name);
Console.WriteLine("==========================================================");
i_1.partner.Name = "Ainy";
i_1.Name = "CC";
i_1.age = 1;
Console.WriteLine("我的name : {0} , copy的name : {1}", i.Name, i_1.Name);
Console.WriteLine("我的Partner的Name : {0} , copy的Partner的age : {1}", i.partner.Name, i_1.partner.Name);
Console.ReadLine();
}
}
}结果 :

只有引用类型 public Person partner { set; get; } 指向的是同一块内存空间 . 值类型及String类型都是指向不同的内存空间.这才是浅拷贝.
深拷贝 : 就是将引用类型指向不同的内存空间,实现完全的Copy.下节解析............
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。