`
netxdiy
  • 浏览: 679932 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

DeepClone与ShadowClone(downmoon)

 
阅读更多

杳MSDN知:
ArrayList.Clone 方法

创建ArrayList 的浅表副本。

命名空间:System.Collections
程序集:mscorlib(在 mscorlib.dll 中)

返回值ArrayList 的浅表副本。

集合的浅表副本仅复制集合的元素(不论它们是引用类型还是值类型),但不复制引用所引用的对象。新集合中的引用与原始集合中的引用指向相同的对象。

与之相对,集合的深层副本将复制这些元素以及由它们直接或间接引用的所有内容。

据此,说明如下 :







下面给出一个完整的例子:

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

namespace CloneObjectTest
... {

// Justaddedtoshowthedifferencebetweenshallowanddeepcloning
[Serializable()]
class SampleRefType
... {
public int Val;
}


[Serializable()]
class Employee
... {
public string m_Name;
public Int16m_age;
public SampleRefTypesomeObject;

public void Print()
... {
Console.WriteLine(
" Name: " + m_Name);
Console.WriteLine(
" Age: " + m_age);
Console.WriteLine(
" SomeValue: " + someObject.Val);
}

// Thisisonewaytododeepcloning.Butworksonlyifthe
// objectsanditsreferencesareserializable
public EmployeeDeepClone()
... {
MemoryStreamm
= new MemoryStream();
BinaryFormatterb
= new BinaryFormatter();
b.Serialize(m,
this );
m.Position
= 0 ;
return (Employee)b.Deserialize(m);
}

// Doshallowcloning
public EmployeeShallowClone()
... {
return (Employee) this .MemberwiseClone();
}

static void Main( string []args)
... {
SampleRefTypeobjRef
= new SampleRefType();
objRef.Val
= 1000 ;
EmployeeobjA
= new Employee();
objA.m_Name
= " Manoj " ;
objA.m_age
= 23 ;
objA.someObject
= objRef;
EmployeeobjB
= objA.DeepClone();
EmployeeobjC
= objA.ShallowClone();
// objBisadeepclone.SochagesmadetoobjRefwouldnotaffectobjB'svalue.
// ButobjCisshallowcloned.So,iftheobjRefischanged,soisthevaluein
// ObjC.SoobjCshouldprint2000whereasobjBshouldprint1000
objRef.Val = 2000 ;

// Updatingsomestate
objC.m_age = 100 ;
objB.m_Name
= " NewName " ;

Console.WriteLine(
" OriginalObject: " );
objA.Print();
Console.WriteLine();
Console.WriteLine(
" ShallowClonedObject: " );
objC.Print();
Console.WriteLine();
Console.WriteLine(
" DeepClonedObject: " );
objB.Print();
}

}

}

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics