Are Member Properties Let- or Use- Bound in F#?
Consider the following example F# code:
type mytype() =
member this.v = new OtherClass()
If OtherClass implements IDisposable, does the member binding act like a let binding or a use binding? Is there any way to get it to act as a use binding? 开发者_运维百科 I have some code very similar to this and I want to insure that the Dispose is called when the parent object goes out of scope.
A quick scan through Expert F# failed to turn up anything definite but perhaps I am looking for the wrong terms in the book.
In your snippet, the body of the member v will be evaluated each time the member is called (meaning that it will create a new instance of OtherClass each time someone uses it). The member simply returns the newly created object and you could use it like this:
let m = new MyType()
use v = m.V // 'use' binding
I'm not sure if this is what you were asking though. If you want to create only a single instance, you'll need to write something like this:
type MyType() =
let v = new OtherClass()
member this.V = v
This behaves as usual let binding and the v value won't be disposed automatically when the current instance of MyType is disposed. To have v automatically disposed, you'll need to implement IDisposable in MyType explicitly:
type MyType() =
let v = new OtherClass()
member this.V = v
interface IDisposable with
member x.Dispose() = (v :> IDisposable).Dispose()
Unfortunately, there is no syntactic sugar that would make it nicer (I once suggested allowing use and implicitly implementing IDisposable for type members to the F# team, but they didn't implement it
(yet:-))).
加载中,请稍侯......
精彩评论