Alo*_*zcz 4 .net f# compiler-errors type-constraints
我想实现一个泛型 F# 类,它的类型参数肯定提供了一个名为“TryParse”的静态方法。除此之外,我希望我的班级在不再需要后得到正确处理。我提出了以下实现:
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
()
Run Code Online (Sandbox Code Playgroud)
问题是:在两个成员(“开始”和“处置”)上,我收到以下错误:
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.
Run Code Online (Sandbox Code Playgroud)
我可以通过用“内联”装饰它来修复它在 Start() 成员上,但是我无法对接口定义做同样的事情。
是否可以强制我的泛型类型实现静态方法并定义类 Disposable ?
如评论中所述,类不能具有静态解析的类型参数。如果你想做这样的事情,一个很好的技巧是有一个内联方法,它有约束并捕获你以后需要在接口中或作为第一类函数的操作。
在你的情况下,你可以改变你的类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() = ()
Run Code Online (Sandbox Code Playgroud)
具有静态内联成员的非泛型类型将是:
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))
Run Code Online (Sandbox Code Playgroud)
假设您有一个Foo具有适当TryParse成员的类型,您可以编写:
let l = Listener.Create<Foo>()
Run Code Online (Sandbox Code Playgroud)