C#之深度复制和浅度复制
2008-09-11 00:27
246 查看
深度复制就是引用类型的复制
浅度复制是值类型的复制
例如:
using System;
using System.Collections.Generic;
using System.Text;
namespace Test
{
public class Content
{
public int val;
}
//此处若是深度复制才继承ICloneable接口
//public class Cloner : ICloneable
public class Cloner
{
public Content MyContent = new Content();
public Cloner(int newVal)
{
MyContent.val = newVal;
}
//浅度复制
//使用System.Object.MemberwiseClone()进行浅度复制,使用getCopy方法.
public object getCopy()
{
return MemberwiseClone();
}
//深度复制:
public object clone()
{
Cloner clonedCloner = new Cloner(MyContent.val); //此处是实例化一个对象
return clonedCloner;
}
}
}
//主函数
using System;
using System.Collections.Generic;
using System.Text;
namespace Test
{
class Program
{
static void Main(string[] args)
{
Cloner mySource = new Cloner(5);
Cloner myTarget = (Cloner)mySource.getCopy();//深度为cloner
Console.WriteLine("MyTarget.Mycontent.Val={}",myTarget.MyContent.val);
mySource.MyContent.val = 2;
Console.WriteLine("MyTarget.Mycontent.Val={}", myTarget.MyContent.val);
}
}
}
浅度复制是值类型的复制
例如:
using System;
using System.Collections.Generic;
using System.Text;
namespace Test
{
public class Content
{
public int val;
}
//此处若是深度复制才继承ICloneable接口
//public class Cloner : ICloneable
public class Cloner
{
public Content MyContent = new Content();
public Cloner(int newVal)
{
MyContent.val = newVal;
}
//浅度复制
//使用System.Object.MemberwiseClone()进行浅度复制,使用getCopy方法.
public object getCopy()
{
return MemberwiseClone();
}
//深度复制:
public object clone()
{
Cloner clonedCloner = new Cloner(MyContent.val); //此处是实例化一个对象
return clonedCloner;
}
}
}
//主函数
using System;
using System.Collections.Generic;
using System.Text;
namespace Test
{
class Program
{
static void Main(string[] args)
{
Cloner mySource = new Cloner(5);
Cloner myTarget = (Cloner)mySource.getCopy();//深度为cloner
Console.WriteLine("MyTarget.Mycontent.Val={}",myTarget.MyContent.val);
mySource.MyContent.val = 2;
Console.WriteLine("MyTarget.Mycontent.Val={}", myTarget.MyContent.val);
}
}
}
相关文章推荐
- 由struct 和class 想到的浅度复制和深度复制 c#
- C#中深度复制和浅度复制详解
- C# (值类型/应用类型/内存框图)与对象深度/浅度复制/系列化/反系列化)
- c#:深度复制和浅度复制
- C# (值类型/应用类型/内存框图)与对象深度/浅度复制/系列化/反系列化)
- [No0000B9]C# 类型基础 值类型和引用类型 及其 对象复制 浅度复制vs深度复制 深入研究2
- c#深度复制 浅度复制
- C# 类型基础(对象深度/浅度复制)
- C#之深度复制和浅度复制
- C# 使用反射来实现对象的深度复制方法
- C#:浅谈对象数组,运算符重载和深度复制的应用
- 一个关于深度复制和浅度复制的例子
- 关于对象的深度复制和浅度复制
- 深度复制与浅度复制
- C#复制和深度复制的实现方法
- (原创)c#学习笔记09--定义类08--浅度和深度复制
- C#读书笔记----浅度复制与深度复制
- 深度复制和浅度复制
- java list 深度复制,浅度复制
- 类对象的深度复制,浅度复制