簡體   English   中英

F# 靜態成員約束結合 IDisposable

[英]F# static member constraints combined with IDisposable

我想實現一個泛型 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
         ()

問題是:在兩個成員(“開始”和“處置”)上,我收到以下錯誤:

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() 成員上,但是我無法對接口定義做同樣的事情。

是否可以強制我的泛型類型實現靜態方法並定義類 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() = ()

具有靜態內聯成員的非泛型類型將是:

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))

假設您有一個具有適當TryParse成員的Foo類型,您可以編寫:

let l = Listener.Create<Foo>()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM