2014-08-28 71 views
1

我想複製包含列表字段的引用類(foo)的實例。列表字段包含另一個類的實例(bar)。使用$copy()方法複製foo實例時,不會複製列表實例並繼續引用同一對象。下面的代碼說明了這個問題。有沒有解決的辦法?我如何做一個真正的深層複製?創建引用類的深層副本:不適用於列表字段?

bar<-setRefClass("bar", fields = list(name = "character")) 
foo<-setRefClass("foo", fields = list(tcp_vector = "list")) 


x1<-foo() 
x1$tcp_vector <- list(bar(name = "test1")) 

x1$tcp_vector[[1]]$name # equals "test1" 

x2 <- x1$copy() 

x2$tcp_vector[[1]]$name # equals "test1" 

x2$tcp_vector[[1]]$name <- "test2" # set to "test2" 

x2$tcp_vector[[1]]$name # equals "test2" 

x1$tcp_vector[[1]]$name # also equals "test2"?? 
+0

沒有關於ref類的線索,如果複製是自動正確實現的,但是你可以用'copy = new(「MicroPlate」)之類的東西來覆蓋它 listOldVars = ls(envir = self @ .data,all.names = T) for(i in listOldVars){ copy @ .data [[i]] = self @ .data [[i]] } return(copy)' – phonixor 2014-08-28 14:41:34

回答

1

copy方法實際上只複製ReferenceClass對象。您的foo類只有一個字段,即list,而「正常」字段不會被複制。此作品:

bar<-setRefClass("bar", fields = list(name = "character")) 
    foo<-setRefClass("foo", fields = list(tcp_vector = "bar")) 
    x1<-foo() 
    x1$tcp_vector <- bar(name = "test1") 
    x1$tcp_vector$name # equals "test1" 
    x2 <- x1$copy() 

    x2$tcp_vector$name # equals "test1" 

    x2$tcp_vector$name <- "test2" # set to "test2" 

    x2$tcp_vector$name # equals "test2" 

    x1$tcp_vector$name # equals "test" 

查看幫助?setRefClass瞭解詳情。如果您想保留在OP中定義的foo類,我想您必須在創建x1的副本之前手動複製任何bar對象。