gpt4 book ai didi

.net - F# 静态成员约束结合 IDisposable

转载 作者:行者123 更新时间:2023-12-02 10:40:38 25 4
gpt4 key购买 nike

我想实现一个通用 F# 类,其类型参数肯定提供了一个名为“TryParse”的静态方法。除此之外,我希望我的类(class)在不再需要后得到正确处理。我想出了以下实现:

type Listener<'a when ^a : (static member TryParse : string -> ^a option)>() =
// construct the object here
let input : string = "" // get input
let res = (^a : (static member TryParse : string -> ^a option) input)

member this.Start() =
// ...
()

interface IDisposable with
member this.Dispose() =
// do cleanup
()
问题是:在两个成员(“开始”和“处置”)上,我收到以下错误:
Error: This code is not sufficiently generic. The type variable  ^a when  ^a : (static member TryParse : string -> ^a option) could not be generalized because it would escape its scope.
我可以通过用“内联”装饰它在 Start() 成员上修复它,但是我无法对接口(interface)定义做同样的事情。
是否可以强制我的泛型类型实现静态方法并定义类 Disposable ?

最佳答案

如评论中所述,类不能具有静态解析的类型参数。如果你想做这样的事情,一个很好的技巧是有一个内联方法,它具有约束并捕获你以后在接口(interface)中需要的操作或作为一等函数。
在您的情况下,您可以更改您的类(class)以参加 tryParse : string -> 'a option作为参数,然后有一个静态方法,可以让您自动捕获支持它的类型:

type Listener<'a>(tryParse : string -> 'a option) =
let input : string = ""
let res = tryParse input

member this.Start() = ()

interface System.IDisposable with
member this.Dispose() = ()
具有静态内联成员的非泛型类型将是:
type Listener = 
static member inline Create< ^b
when ^b : (static member TryParse : string -> ^b option)>() =
new Listener< ^b >(fun input ->
(^b : (static member TryParse : string -> ^b option) input))
假设你有一个类型 Foo与适当的 TryParse成员(member),你可以写:
let l = Listener.Create<Foo>()

关于.net - F# 静态成员约束结合 IDisposable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63692221/

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