2010-10-10 64 views
1

我使用this.MemberwiseClone()来创建shallowcopy,但它不工作。请看下面的代码。.net memberwiseclone浅拷贝不工作

public class Customer 
    { 

     public int Id; 
     public string Name; 

     public Customer CreateShallowCopy() 
     { 
      return (Customer)this.MemberwiseClone(); 
     } 
    } 

class Program 
{ 
    static void Main(string[] args) 
    { 
     Customer objCustomer = new Customer() { Id = 1, Name = "James"}; 
     Customer objCustomer2 = objCustomer; 

     Customer objCustomerShallowCopy = objCustomer.CreateShallowCopy(); 

     objCustomer.Name = "Jim"; 
     objCustomer.Id = 2;    
    } 
} 

当我运行程序时,它显示objCustomerShallowCopy.Name为“詹姆斯”,而不是“吉姆”。

任何想法?

回答

2

当您复制Customer对象时,objCustomerShallowCopy.Name将为James,并将保持原样,直到您更改该对象。现在在你的情况下,字符串“James”将给它3个引用(objCustomer,objCustomer2和objCustomerShallowCopy)。

当您将objCustomer.Name更改为Jim时,实际上是为objCustomer对象创建了一个新的字符串对象,并向“James”字符串对象释放1个引用。

+0

我该如何去改变“objCustomer”属性(引用类型),以便我可以看到反映在“objCustomerShallowCopy”中的更改? – Subhasis 2010-10-10 16:58:39

+0

在这种情况下,为什么首先使用克隆?只需设置objCustomerShallowCopy = objCustomer – 2010-10-10 17:02:12

+0

为什么文档说MemberwiseClone做了浅拷贝,而实际上它没有做。它正在做一个深层次的复制。 – Subhasis 2010-10-10 17:06:27

0

我们也遇到了问题,工作。我们通过序列化然后反序列化对象来解决它。

public static T DeepCopy<T>(T item) 
{ 
    BinaryFormatter formatter = new BinaryFormatter(); 
    MemoryStream stream = new MemoryStream(); 
    formatter.Serialize(stream, item); 
    stream.Seek(0, SeekOrigin.Begin); 
    T result = (T)formatter.Deserialize(stream); 
    stream.Close(); 
    return result; 
} 

使用上述代码会有两个对象之间没有引用。