对象复制(所谓的克隆-Clone)
2005-08-30 16:31 灵感之源 阅读(5125) 评论(10) 编辑 收藏 举报
对象复制,最generic的方法,估计是继承ICloneable,然后写Clone函数。
但当该函数不能修改,如是第三方组件中的类,或者因为其它原因,我们就被迫采取别的方法了。
如果碰巧对象实现了ISerializable,那么我们可以:
private static void TestClone()
{
Person p1 = new Person();
p1.Age = 26;
p1.UserName = "灵感之源";
Person p2 = (Person)CloneObjectEx(p1);
p2.UserName = "unruledboy";
Console.WriteLine(p1.UserName);
Console.WriteLine(p2.UserName);
}
public static Person CloneObject(Person ObjectInstance)
{
BinaryFormatter bFormatter = new BinaryFormatter();
MemoryStream stream = new MemoryStream();
bFormatter.Serialize(stream, ObjectInstance);
stream.Seek(0, SeekOrigin.Begin);
Person newObject = (Person)bFormatter.Deserialize(stream);
return newObject;
}
public static object CloneObjectEx(object ObjectInstance)
{
BinaryFormatter bFormatter = new BinaryFormatter();
MemoryStream stream = new MemoryStream();
bFormatter.Serialize(stream, ObjectInstance);
stream.Seek(0, SeekOrigin.Begin);
return bFormatter.Deserialize(stream);
}
CloneObject和CloneObjectEx的区别在于:CloneObject返回的是强类型,但限制为指定的类型,不通用;后者通用,但性能要更加低。
或者显式采用反射来逐个获取对象的每个属性:
Base class for cloning an object in C#
如果对象连ISerializable都没有实现,那么我们只能:
How to serialize an object which is NOT marked as 'Serializable' using a surrogate
如果上述的方法都不满意,请你研究得出结果之后告诉我;)
但当该函数不能修改,如是第三方组件中的类,或者因为其它原因,我们就被迫采取别的方法了。
如果碰巧对象实现了ISerializable,那么我们可以:
private static void TestClone()
{
Person p1 = new Person();
p1.Age = 26;
p1.UserName = "灵感之源";
Person p2 = (Person)CloneObjectEx(p1);
p2.UserName = "unruledboy";
Console.WriteLine(p1.UserName);
Console.WriteLine(p2.UserName);
}
public static Person CloneObject(Person ObjectInstance)
{
BinaryFormatter bFormatter = new BinaryFormatter();
MemoryStream stream = new MemoryStream();
bFormatter.Serialize(stream, ObjectInstance);
stream.Seek(0, SeekOrigin.Begin);
Person newObject = (Person)bFormatter.Deserialize(stream);
return newObject;
}
public static object CloneObjectEx(object ObjectInstance)
{
BinaryFormatter bFormatter = new BinaryFormatter();
MemoryStream stream = new MemoryStream();
bFormatter.Serialize(stream, ObjectInstance);
stream.Seek(0, SeekOrigin.Begin);
return bFormatter.Deserialize(stream);
}
[Serializable]
public class Person
{
private int age;
private string userName;
public Person()
{
}
public int Age
{
get{return age;}
set{age = value;}
}
public string UserName
{
get{return userName;}
set{userName = value;}
}
}
public class Person
{
private int age;
private string userName;
public Person()
{
}
public int Age
{
get{return age;}
set{age = value;}
}
public string UserName
{
get{return userName;}
set{userName = value;}
}
}
CloneObject和CloneObjectEx的区别在于:CloneObject返回的是强类型,但限制为指定的类型,不通用;后者通用,但性能要更加低。
或者显式采用反射来逐个获取对象的每个属性:
Base class for cloning an object in C#
如果对象连ISerializable都没有实现,那么我们只能:
How to serialize an object which is NOT marked as 'Serializable' using a surrogate
如果上述的方法都不满意,请你研究得出结果之后告诉我;)