在球拍中可以同时获取一个对象的所有字段吗?
基本上,我希望将一个对象转换为一个哈希表,其中字段名作为键,字段值作为值。
我找到了一个函数( field -names ),但是我不知道如何使用返回的字段名从obj中获取值。函数get-field可以用来获取字段的值,但我不知道如何将它与值一起使用:
> (define x% (class object% (init-field x y) (super-new)))
> (define obj (make-object x% 1 2))
> (get-field x obj)
1
> (field-names obj)
'(y x)
> (define field-name (second (field-names obj)))
> field-name
'x
> (get-field field-name obj)
get-field: given object does not have the requested field
field name: field-name
object: (object:x% ...)
errortrace...:
context...:
/usr/lib/racket/collects/racket/private/class-internal.rkt:4906:0: obj-error29
/usr/lib/racket/collects/racket/private/misc.rkt:87:7发布于 2012-09-06 00:23:12
下面是一些帮助您入门的代码
#lang racket
> (define x% (class object% (inspect #f) (init-field x y) (super-new)))
> (define obj (make-object x% 1 2))
> (let-values (((name field-cnt field-name-list field-accessor field-mutator super-class skipped)
(class-info x%)))
(for/hash ((name field-name-list)
(idx field-cnt))
(values name (field-accessor obj idx))))
'#hash((x . -1) (y . 0))您可能想要将检查器从#f更改为较不容易受到攻击的对象,但要根据您的需要进行足够的开放。阅读有关class-info和检查器的一般信息。
https://stackoverflow.com/questions/12283592
复制相似问题