补:依托串行实现Person类的clone
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Serialization.Formatters.Soap;
using System.IO;
using System.Runtime.Serialization;
namespace SerializableTest
{
class Program
{
static void Main(string[] args)
{
SeriMethod();
DeseriMethod();
Person riObj = new Person(56, "DongDavid");
Person cloneObj = (Person)oriObj.Clone();
oriObj.name = "ChangeName";
Console.WriteLine(cloneObj.age + cloneObj.name);
Console.WriteLine(oriObj.age + oriObj.name);
}
static void SeriMethod()
{
Person per = new Person(27, "David");
Stream str = File.Open(@"C:\SerializableTest.dat", FileMode.Create);
BinaryFormatter bf = new BinaryFormatter();
bf.Serialize(str, per);
Person perSoap = new Person(37, "Old David");
Stream strSoap = File.Open(@"C:\SerializableTest_Soap.dat", FileMode.Create);
SoapFormatter soapFor = new SoapFormatter();
soapFor.Serialize(strSoap, perSoap);
str.Close();
strSoap.Close();
}
static void DeseriMethod()
{
Stream str = File.Open(@"C:\SerializableTest.dat", FileMode.Open);
Stream strSoap = File.Open(@"C:\SerializableTest_Soap.dat", FileMode.Open);
BinaryFormatter bf = new BinaryFormatter();
SoapFormatter soapFor = new SoapFormatter();
object o = bf.Deserialize(str);
object Soap = soapFor.Deserialize(strSoap);
Person per = (Person)o;
Person perSoap = (Person)oSoap;
if (per != null)
Console.WriteLine("Binary DeSerialized Person aged:{0} name:{1}", per.age, per.name);
if (perSoap != null)
Console.WriteLine("Soap DeSerialized Person aged:{0} name:{1}", perSoap.age, perSoap.name);
str.Close();
strSoap.Close();
}
}
[Serializable]
class Person : ISerializable
{
public int age;
//[NonSerialized]
public string name = string.Empty;
public Person(int argAge, string argName)
{
age = argAge;
name = argName;
}
#region ISerializable Members
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
info.AddValue("age", age);
info.AddValue("name", name);
}
private Person(SerializationInfo info, StreamingContext context)
{
age = info.GetInt32("age");
name = info.GetString("name");
}
#endregion
public object Clone()
{
MemoryStream stream = new MemoryStream();
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(stream, this);
stream.Position = 0;
return formatter.Deserialize(stream);
}
}
}
来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/12476590/viewspace-586467/,如需转载,请注明出处,否则将追究法律责任。
转载于:http://blog.itpub.net/12476590/viewspace-586467/