F#静态成员约束结合IDisposable
F# static member constraints combined with IDisposable
我想实现一个泛型 F# class,其类型参数肯定会提供一个名为“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
()
问题是:在两个成员(“Start”和“Dispose”)上我都收到以下错误:
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() 成员上,但是我无法对接口定义做同样的事情。
是否可以强制我的泛型类型实现静态方法并定义 class Disposable?
如评论中所述,classes 不能具有静态解析的类型参数。如果你想做这样的事情,一个好的技巧是有一个内联方法,它有约束并捕获你以后需要在接口中或作为 first-class 函数的操作。
在您的情况下,您可以更改 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() = ()
具有静态内联成员的 non-generic 类型将是:
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
成员,你可以写:
let l = Listener.Create<Foo>()
我想实现一个泛型 F# class,其类型参数肯定会提供一个名为“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
()
问题是:在两个成员(“Start”和“Dispose”)上我都收到以下错误:
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() 成员上,但是我无法对接口定义做同样的事情。
是否可以强制我的泛型类型实现静态方法并定义 class Disposable?
如评论中所述,classes 不能具有静态解析的类型参数。如果你想做这样的事情,一个好的技巧是有一个内联方法,它有约束并捕获你以后需要在接口中或作为 first-class 函数的操作。
在您的情况下,您可以更改 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() = ()
具有静态内联成员的 non-generic 类型将是:
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
成员,你可以写:
let l = Listener.Create<Foo>()