无法访问F#类中的Dispose方法

Dar*_*ren 6 f# dispose

我在F#中创建了一个实现IDisposable接口的类.该类被正确清理,use关键字能够访问Dispose方法.我有第二个用例,我需要显式调用Dispose方法,我无法在下面的示例中.似乎在课堂上没有Dipose方法.

open System

type Foo() = class
    do
        ()

    interface IDisposable with
        member x.Dispose() =
            printfn "Disposing"

end

let test() =
    // This usage is ok, and correctly runs Dispose()
    use f = new Foo()


    let f2 = new Foo()
    // The Dispose method isn't available and this code is not valid
    // "The field , constructor or member Dispose is not defined."
    f2.Dispose()

test()
Run Code Online (Sandbox Code Playgroud)

Tom*_*cek 10

在F#类中实现接口更类似于C#中的显式接口实现,这意味着接口的方法不会成为方法的公共类.要调用它们,您需要将类强制转换为接口(不能失败).

这意味着,要打电话Dispose你需要写:

(f2 :> IDisposable).Dispose()
Run Code Online (Sandbox Code Playgroud)

在实践中,这不是经常需要的,因为use关键字确保Dispose在值超出范围时自动调用,所以我会写:

let test() =
  use f2 = new Foo()
  f2.DoSomething()
Run Code Online (Sandbox Code Playgroud)

这里,f2test函数返回时被释放.