[英]F# constructor syntax - overiding and augmenting new
I have a non-disposable class with Open/Close syntax that I'd like to be able to use
, so I'm trying to inherit from it, and work the Open into the new
and the Close into Dispose. 我有一个非一次性的类,我希望能够use
Open / Close语法,所以我试图继承它,并将Open打开到new
和Close into Dispose。
The second part is ok, but I can't work out how to do the Open: 第二部分没问题,但我无法解决如何进行Open:
type DisposableOpenCloseClass(openargs) =
inherit OpenCloseClass()
//do this.Open(openargs) <-- compiler no like
interface IDisposable
with member this.Dispose() = this.Close()
(cf. this question which I asked a long time ago, but I can't join the dots to this one) (参考我很久以前问过的这个问题 ,但我不能加入这个问题)
Key is as this
: 关键是as this
:
type OpenCloseClass() =
member this.Open(x) = printfn "opened %d" x
member this.Close() = printfn "closed"
open System
type DisposableOpenCloseClass(openargs) as this =
inherit OpenCloseClass()
do this.Open(openargs)
interface IDisposable
with member this.Dispose() = this.Close()
let f() =
use docc = new DisposableOpenCloseClass(42)
printfn "inside"
f()
As Brian suggests, you can use the as this
clause. 正如Brian建议的那样,你可以使用as this
子句。 However, in F#, it is usually recomended to use subclassing (inheritance) only when there is a really good reason for that (eg you need to implement some virtual class and pass it to a .NET library). 但是,在F#中,通常建议仅在有充分理由的情况下使用子类化(继承)(例如,您需要实现一些虚拟类并将其传递给.NET库)。
If I was implementing your example, I would probably prefer function returning IDisposable
using a simple object expression : 如果我正在实现您的示例,我可能更喜欢使用简单对象表达式返回IDisposable
函数:
let disposableOpenClose(openargs) =
let oc = new OpenCloseClass()
oc.Open(openargs)
{ new IDisposable with
member this.Dispose() = oc.Close() }
let f() =
use docc = disposableOpenClose(42)
printfn "inside"
To some point, this is just a personal preference, but I think it is a preferred option, because it is simpler than using inheritance (although I don't have any document to link here :-)). 在某种程度上,这只是个人偏好,但我认为它是一个首选的选项,因为它比使用继承更简单(虽然我没有任何文档链接在这里:-))。 Also, the compiled code may be a bit simpler, because handling as this
may require some runtime checks. 此外,编译的代码可能有点简单,因为处理as this
可能需要一些运行时检查。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.