C#中如何对数组进行深复制
时间:2011-03-05 来源:Ellic
using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
namespace ArraySample
{
[Serializable] //标识Number类为可序列化
class Number
{
public int Num{get;set;}
public override string ToString()
{
return string.Format("数值为:{0}",Num);
}
}
class CopySample
{
public static void PrintArray(Number [] Numbers)
{
foreach(Number number in Numbers)
{
Console.WriteLine(number);
}
Console.WriteLine();
}
public static void Main(string[] args)
{
Number[] array1 = new Number[4];
int[] array2 = new int[4]{1,2,3,4};
for(int i=0;i<array1.Length;i++)
{
array1[i] = new Number{Num = 10 *(i+1)};
}
Console.WriteLine("数组array1的元素:");
PrintArray(array1);
MemoryStream ms = new MemoryStream();//序列化
BinaryFormatter bf = new BinaryFormatter();
bf.Serialize(ms,array1);
ms.Position = 0;
Number[] array3 = (Number[])bf.Deserialize(ms); //反序列化
for(int i = 0;i<array3.Length;i++)
{
array3[i].Num=20 *(i+1);
}
Console.WriteLine("对数组array3进行重新赋值后array3的元素:");
PrintArray(array3);
Console.WriteLine("对数组array3进行重新赋值后array1的元素:");
PrintArray(array1);
Console.Write("Press any key to continue . . . ");
Console.ReadKey(true);
}
}
}
相关阅读 更多 +