7

我在 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()
4

2 回答 2

10

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

这意味着,要调用Dispose您需要编写:

(f2 :> IDisposable).Dispose()

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

let test() =
  use f2 = new Foo()
  f2.DoSomething()

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

于 2013-01-22T03:23:31.173 回答
1

托马斯说得对。仅供参考,您可以在您的类型上实现 Dispose() 函数以便于使用:

member x.Dispose() = (x :> IDisposable).Dispose()

那是IDisposable. 然后你就可以写了f2.Dispose()

于 2014-01-08T17:05:17.020 回答