gen:custom-write 用于 Racket 类 [英] gen:custom-write for Racket classes

查看:29
本文介绍了gen:custom-write 用于 Racket 类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找指定自定义方法以输出 Racket 对象字段的规范方法.换句话说,我正在寻找 Java 的 toString 方法(如果存在)的 Racket 等价物.

I am looking for the canonical way to specify custom methods to output the fields of a Racket object. In other words I'm looking for the Racket equivalent of Java's toString method (if it exists).

我知道对于结构体可以使用 gen:custom-write 来指定 write-proc 函数(source).类有类似的东西吗?

I know that for structs one can use gen:custom-write to specify the write-proc function (source). Is there something similar for classes?

推荐答案

Yes for custom-write.由于 gen:custom-writeprop:custom-write,可以让一个类通过接口实现它.

Yes for custom-write. Since gen:custom-write is a wrapper around prop:custom-write, it is possible to have a class implement it through an interface.

可打印<%>接口实现 prop:custom-write 允许这样的事情:

The printable<%> interface implements prop:custom-write to allow things like this:

#lang racket

(define fish%
  (class* object% (printable<%>)
    (super-new)
    (define/public (custom-print out depth)
      (fprintf out "><,`>"))
    (define/public (custom-write out)
      (fprintf out "><,`>"))
    (define/public (custom-display out)
      (fprintf out "><,`>"))))

使用:

> (new fish%)
><,`>

这是可能的,因为 printable<%> 接口使用 interface* 形式继承自 prop:custom-write 结构类型属性.然而,这并非适用于所有通用接口,仅适用于与 struct-type-properties 对应的接口.

This is possible because the printable<%> interface uses the interface* form to inherit from the prop:custom-write struct-type property. However, this is not true for all generic interfaces, just the ones that correspond to struct-type-properties.

附言不要太担心文档说 prop:custom-write 已弃用.用户"没有必要使用它,因为 gen:custom-write 存在于结构和 printable<%> 存在于类中.它作为接口已被弃用,但作为实现它不会消失.这样就可以安全"地使用而不必担心.

P.S. Don't worry too much about the documentation saying prop:custom-write is deprecated. It's just not necessary for "users" to use it, since gen:custom-write exists for structs and printable<%> exists for classes. It's deprecated as an interface, but as an implementation it is not going away. In that way it's "safe" to use without worrying.

这篇关于gen:custom-write 用于 Racket 类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆