F#等价的析构函数

时间:2011-04-15 12:34:08

标签: f# finalizer c#-to-f#

我正在翻译一个将非托管库包装到F#的C#类。我遇到了重写后面的析构函数这个看似简单的问题。

class Wrapper {

    // P/Invoke ellided

    private SomeType x;

    public Wrapper() {
        x = new SomeType();
        Begin();
    }

    public ~Wrapper() {
        End();
    }

此时简化的F#代码如下:

type Wrapper() =
  [<Literal>]
  static let wrappedDll = "Library.dll"

  [<DllImport(wrappedDll , EntryPoint = "Begin")>]
  static extern void Begin()

  [<DllImport(wrappedDll , EntryPoint = "End")>]
  static extern void End()

  let x = new SomeType()

  do
    Begin()

如何修改此F#代码以具有相同的行为?我对F#析构函数的搜索结果没有出现在我的书籍或网络上。

谢谢。

2 个答案:

答案 0 :(得分:18)

您是否尝试过寻找F#终结者?

override x.Finalize() = ...

答案 1 :(得分:10)

namespace FSharp.Library  

type MyClass() as self = 

    let mutable disposed = false;

    // TODO define your variables including disposable objects

    do // TODO perform initialization code
        ()

    // internal method to cleanup resources
    let cleanup(disposing:bool) = 
        if not disposed then
            disposed <- true

            if disposing then
                // TODO dispose of managed resources
                ()

            // TODO cleanup unmanaged resources
            ()

    // implementation of IDisposable
    interface IDisposable with
        member self.Dispose() =
            cleanup(true)
            GC.SuppressFinalize(self)

    // override of finalizer
    override self.Finalize() = 
        cleanup(false)

F#类库模板

http://blogs.msdn.com/b/mcsuksoldev/archive/2011/06/05/f-class-library-template.aspx