2010-10-10 102 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; 
} 

使用上述代碼會有兩個對象之間沒有引用。