日期:2014-05-17  浏览次数:20832 次

深度复制,当一个对象A有N多个属性是,我要把对象A复制给B,除了反射机制还有其他的方法?
本帖最后由 SCAUSCNU 于 2012-11-22 20:39:49 编辑 深度复制,当一个对象A有N多个属性是,我要把对象A复制给B,(就是改变B不会影响到A)除了反射机制还有其他的方法?
反射机制不怎么看得懂,依次把对象A的属性赋值给B的属性又觉得太麻烦了,大家有什么好的办法吗?
------最佳解决方案--------------------
public T DeepCopy<T>(T arg)
{
BinaryFormatter formatter = new BinaryFormatter();
MemoryStream stream = new MemoryStream();
formatter.Serialize(stream, arg);
stream.Position = 0;
T result = (T)formatter.Deserialize(stream);
stream.Close();
return result;
}

------其他解决方案--------------------
序列化拷贝,再反序列化。不过效率比较低。

http://blog.csdn.net/fangxinggood/article/details/369410
------其他解决方案--------------------
写程序首先考虑的是程序的正确性而不是怎么方便,看如下代码:
class A
{
    public B Obj { get; set; }
}
class B
{
    public string Text { get; set; }
}

A a1, a2;
a1 = new A() { Obj = new B() { Text = "a1" }};
如果A不是你设计的,请问你打算怎么复制a2?不要问我,我也不知道。
------其他解决方案--------------------
引用:
C# code?12345678910public T DeepCopy<T>(T arg){    BinaryFormatter formatter = new BinaryFormatter();    MemoryStream stream = new MemoryStream();    formatter.Serialize(stream, arg);    ……


我了个去,这都可以,学习了,哈哈,序列化的巧妙运用啊
------其他解决方案--------------------
引用:
写程序首先考虑的是程序的正确性而不是怎么方便,看如下代码:
class A
{
    public B Obj { get; set; }
}
class B
{
    public string Text { get; set; }
}

A a1, a2;
a1 = new A() { Obj = new B() { Text = "a1" }};
如果A不是你设计……

写个方法,将值移动到新对象上去。
------其他解决方案--------------------
哈哈,1楼跟我想的一样
------其他解决方案--------------------
引用:
写程序首先考虑的是程序的正确性而不是怎么方便,看如下代码:
class A
{
    public B Obj { get; set; }
}
class B
{
    public string Text { get; set; }
}

A a1, a2;
a1 = new A() { Obj = new B() { Text = "a1" ……

其实我的问题没那么复杂,就是比如:
A a1;
a1(就是A)的属性有 int number1,number2,number3,
string  str1,str2,str3,
自定义的类型Student s1,s2,s3;

现在我如果用A a2=a1,那么我改变a2有可能导致改a1,我现在的想法就是改变a2,不影响a1?在创建a2的时候,不希望遍历a1的全部属性赋值给a2,正在看2楼的代码
------其他解决方案--------------------
引用:
C# code?12345678910public T DeepCopy<T>(T arg){    BinaryFormatter formatter = new BinaryFormatter();    MemoryStream stream = new MemoryStream();    formatter.Serialize(stream, arg);    ……