gpt4 book ai didi

interface - 带有静态成员的 F# 接口(interface)

转载 作者:行者123 更新时间:2023-12-03 23:48:07 25 4
gpt4 key购买 nike

如何在接口(interface)中定义静态成员?
为什么不可能?

我想强制 F# 类型(类)具有静态方法来从字符串(JSON 解析)创建自身的实例。
我想要这个接口(interface)示例:

[<Interface>]
type public ILikeJson<'T> =
abstract member ToJson: unit -> string // OK
static abstract member FromJson: string -> 'T // <-- "static" is not valid here !

或者,来自字符串的构造函数可以完成工作,但静态方法听起来更好,因为它将具有适当的名称,而且我也不知道如何在接口(interface)中定义构造函数。

最佳答案

目前的 CLR 规范声明接口(interface)只为对象实例实现,并不适用于类型本身。

C# 8 提出了定义静态接口(interface)成员的建议,但需要在接口(interface)定义本身内提供静态方法的实现。所以你将无法实现 FromJson每个类的方法。

如果你在 F# 中尝试这个,你会得到:

FS0868: Interfaces cannot contain definitions of concrete members. You may need to define a constructor on your type to indicate that the type is a class.



解决此问题的一种方法是使用 static type constraints .它们允许您在类型上查找方法的存在。
let inline create< ^T when ^T : (static member FromJson: string -> ^T)> json = 
(^T : (static member FromJson: string -> ^T) (json))

这支持任何具有静态方法的类型 FromJsonstring -> T签名。
type Number(num: double) =
member _.Value = num
static member FromJson (json) = new Number(Double.Parse(json))

并使用:
create<Number> "1.5" //creates a Number(1.5)

关于interface - 带有静态成员的 F# 接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61291593/

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