gpt4 book ai didi

interface - 满足隐式接口(interface)而无需重新实现的记录

转载 作者:行者123 更新时间:2023-12-04 23:49:36 27 4
gpt4 key购买 nike

看到一条记录的字段已经有一个公共(public)的 Getter/(Setter),是否可以在不重新实现的情况下指定一条记录满足匹配的接口(interface)?

例如:

type IText = 
abstract text : string with get,set

type TextRec =
{
mutable text : string
}

现在看到 Record 已经隐式实现了这个接口(interface),我想在记录上放一个“继承 IText”或“接口(interface) IText”(没有正文),但似乎我不能这样做。事实上,我相信我必须通过将其添加到记录中来重新实现接口(interface):
interface IText with
member this.text
with get() = this.text
and set(v) = this.text <- v

谢谢

最佳答案

F# 目前不支持隐式接口(interface)实现(甚至不支持类),但它是 frequently requested features 之一,所以将来可能会发生。我当然明白为什么这会有用。

我认为没有任何好的解决方法 - 最好的选择可能是编写实现接口(interface)所需的额外代码。

如果您想冒险,您可以尝试编写一个“包装”函数,该函数从提供所需成员的值创建接口(interface)实现。使用静态成员约束,您可以要求成员存在(无需实际实现接口(interface)):

type IText = 
abstract Text : string with get, set

let inline wrap (a:^T) =
{ new IText with
member x.Text
with get() = (^T : (member Text : string) (a))
and set(v) = (^T : (member set_Text : string -> unit) (a, v)) }

静态成员约束(在 wrap 的实现中使用)主要用于通用数值计算,所以这有点牵强(当然也是高级 F# 功能),但它可以解决问题:
type Rect = { mutable Text : string }
let i = wrap { Text = "Hi" }
i.Text <- i.Text + " there!"

关于interface - 满足隐式接口(interface)而无需重新实现的记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25770428/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com