我需要编写一种同时更新对象并返回值的方法。我想知道是否有办法在 S4 课程中做到这一点。这样做的背景是我正在尝试编写一个 S4 类来生成一个列表,只有在知道私钥的情况下才能访问其中的每个元素。为此,我需要一个方法 getNewSlot 来同时更新列表和键列表的长度并返回索引键对。代码如下:
setClass("ProtectedRObjectList",
representation(objectList = "list", keys = "character", length = "numeric"))
setGeneric(
name = "getNewSlot",
def = function(object,value){standardGeneric("getNewSlot")})
setMethod(
f = "getNewSlot",
signature = "ProtectedRObjectList",
definition = function(object){
if(length(object@length)==0)
{
#initial case
object@length <- 0;
}
#update list length and generate random key
object@length<-object@length + 1;
object@keys[object@length]<-paste(sample(c(letters, LETTERS), 15, replace =TRUE), collapse = "");
#return "index, key" pair
return(list("index" = object@length, "key" = object@keys[object@length]))
}
)
这是此方法的输出。如您所见,代码返回所需的“索引、键”对,但不更新对象。
> thisObj<-new("ProtectedRObjectList")
> thisObj
An object of class "ProtectedRObjectList"
Slot "objectList":
list()
Slot "keys":
character(0)
Slot "length":
numeric(0)
> output<-getNewSlot(thisObj)
> output
$index
[1] 1
$key
[1] "cjdkDvAaNjvVKdw"
> thisObj
An object of class "ProtectedRObjectList"
Slot "objectList":
list()
Slot "keys":
character(0)
Slot "length":
numeric(0)