更新:2010 年 5 月
建立延遲計算,用於強制評估所指定值的結果。
命名空間/模組路徑: Microsoft.FSharp.Control.LazyExtensions
組件:FSharp.Core (在 FSharp.Core.dll 中)
// Signature:
type System.Lazy with
member static CreateFromValue : Lazy<'T>
// Usage:
lazy.CreateFromValue (value)
參數
value
型別:'T輸入值。
傳回值
所建立的 Lazy 物件。
範例
下列程式碼範例會說明如何使用 Lazy.CreateFromValue延伸方法。 在此的範例字典用來儲存先前計算的值。 階乘的函式呼叫時,如果已經計算這個值,然後 Lazy.CreateFromValue呼叫與 快取的結果。 如果沒有已計算值然後 Lazy.Create用
let cacheMap = new System.Collections.Generic.Dictionary<_, _>()
cacheMap.Add(0, 1I)
cacheMap.Add(1, 1I)
let lazyFactorial n =
let rec factorial n =
if cacheMap.ContainsKey(n) then cacheMap.[n] else
let result = new System.Numerics.BigInteger(n) * factorial (n - 1)
cacheMap.Add(n, result)
result
if cacheMap.ContainsKey(n) then
printfn "Reading factorial for %d from cache." n
Lazy.CreateFromValue(cacheMap.[n])
else
printfn "Creating lazy factorial for %d." n
Lazy.Create (fun () ->
printfn "Evaluating lazy factorial for %d." n
let result = factorial n
result)
printfn "%A" ((lazyFactorial 12).Force())
printfn "%A" ((lazyFactorial 10).Force())
printfn "%A" ((lazyFactorial 11).Force())
printfn "%A" ((lazyFactorial 30).Force())
輸出
平台
Windows 7、Windows Vista SP2、Windows XP SP3、Windows XP x64 SP2、Windows Server 2008 R2、Windows Server 2008 SP2、Windows Server 2003 SP2
版本資訊
F# 執行階段
支援版本:2.0
Silverlight
支援版本:3
請參閱
參考
Control.LazyExtensions 模組 (F#)
變更記錄
日期 |
History |
原因 |
|---|---|---|
|
2010 年 5 月 |
加入程式碼範例。 |
資訊加強。 |