类实现接口
类实现了一个接口来满足接口的契约。例如,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 -> ()