Get all object fields

Is it possible to get all the fields of an object in a racket at the same time?

I would like to basically convert the object to a hash table with field names as keys and field values ​​as values.

I found a function (obj field names), but then I do not know how to use returned field names to get values ​​from obj. The get-field function can be used to get the value of a field, but I don't know how to use it with a value:

 > (define x% (class object% (init-field xy) (super-new))) > (define obj (make-object x% 1 2)) > (get-field x obj) 1 > (field-names obj) '(yx) > (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 
+4
source share
1 answer

Here is the code to get you started.

 #lang racket > (define x% (class object% (inspect #f) (init-field xy) (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)) 

You might want to change the C # f inspector to something less vulnerable, but open enough to your needs. Read class information and inspectors in general.

+6
source

Source: https://habr.com/ru/post/1432497/


All Articles