如何將下面的代碼(使用c#HtmlAgility庫)轉換爲優雅的樣式?如何使用Option.map和Option.bind重寫多個空檢查?
if node <> null then
let nodes = node.SelectNodes("//input[@name='xxx']")
if nodes <> null then
let first = nodes.[0]
if first <> null then
let value = first.Attributes.["value"]
if value <> null then
Some value.Value
else
None
else
None
else
None
else
None
下面的代碼可能工作嗎?但是,它仍然不像C#6的?.
運營商那樣簡潔。
let toOpt = function null -> None | x -> Some x
node |> toOpt
|> Option.map (fun x -> x.SelectNodes("//input[@name='xxx']") |> toOpt)
|> Option.map (fun x -> x.[0] |> toOpt)
|> Option.map (fun x -> x.Attributes.["value"] |> toOpt)
|> Option.map (fun x -> x.Value |> toOpt)
C#6版本仍然是簡潔得多:
node?.SelectNodes("//input[@name='xxx']")[0]?.Attributes["value"]?.Value
能Option.bind
幫助?
任何人都可以詳細說明「拋開這樣一個運營商是否是一個好主意的爭論」嗎?有沒有更好的方法來做到這一點?由於可以不能從c#中刪除。 – ca9163d9
在C#或任何其他促進/允許使用可空類型的語言中,我認爲''.''是更好的折衷之一。在慣用的F#中不應該使用'null'。然而''。''可以在F#中用於'option'類型,但我認爲首選的習慣用法是提升。 – FuleSnabel