C#浅拷贝-创新互联
浅拷贝和深拷贝主要体现在引用成员上.先上例子:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace CopyDemo
{
///
/// 人类
///
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
{
///
/// 人类
///
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.下节解析............
另外有需要云服务器可以了解下创新互联scvps.cn,海内外云服务器15元起步,三天无理由+7*72小时售后在线,公司持有idc许可证,提供“云服务器、裸金属服务器、高防服务器、香港服务器、美国服务器、虚拟主机、免备案服务器”等云主机租用服务以及企业上云的综合解决方案,具有“安全稳定、简单易用、服务可用性高、性价比高”等特点与优势,专为企业上云打造定制,能够满足用户丰富、多元化的应用场景需求。
新闻名称:C#浅拷贝-创新互联
URL网址:http://www.jxjierui.cn/article/diehjd.html


咨询
建站咨询
