2012-09-05 89 views
4

球拍可以同時獲取對象的所有字段嗎?獲取對象的所有字段

我想基本上將對象轉換爲哈希表,其中字段名稱作爲鍵和字段值作爲值。

我找到了一個函數(field-names obj),但後來我不知道如何使用返回的字段名來獲取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 

回答

6

下面是一些代碼,讓你開始

#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更改爲不易受損的部分,但足夠滿足您的需求。一般瞭解班級信息和檢查員。

+0

檢查員的事情充其量是棘手。沒有真實的文件和/或用例/良好實踐模式。 –