類實現介面

類實現了一個介面來滿足介面的契約。例如,C#類可以實現 IDisposable

public class Resource : IDisposable
{ 
    private MustBeDisposed internalResource;
    
    public Resource() 
    { 
        internalResource = new MustBeDisposed();
    }

    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }

    protected virtual void Dispose(bool disposing){
        if (disposing){
            if (resource != null) internalResource.Dispose();
        }
    }
}

要在 F#中實現介面,請在型別定義中使用 interface

type Resource() = 
    let internalResource = new MustBeDisposed()

    interface IDisposable with
        member this.Dispose(): unit = 
            this.Dispose(true)
            GC.SuppressFinalize(this)

    member __.Dispose disposing = 
        match disposing with 
        | true  -> if (not << isNull) internalResource then internalResource.Dispose()
        | false -> ()