5

在 C# 中,我可以这样表达:

var xe = XElement.Parse("<foo></foo>");
var maybe = (bool?)xe.Element("bar");

这如何在 F# 中表达?

编辑:我确实找到了这个辅助函数

let inline conv (x : ^a) : ^b = ((^a or ^b) : (static member op_Explicit : ^a -> ^b) (x))
4

1 回答 1

6

不幸的是,XLinq 严重依赖隐式和显式转换,这让事情变得有点困难。

您可以创建一个例程将 XElement 转换为 bool 选项:

let elementToBool e =
  match e with
    | null -> None
    | e -> Some(XElement.op_Explicit e : bool)

有了这个,你可以写:

let xe = XElement.Parse("<foo><baz>true</baz></foo>")
let bar = xe.Element (XName.op_Implicit "bar") |> elementToBool
let baz = xe.Element (XName.op_Implicit "baz") |> elementToBool

在 F# Interactive 中,这将转换为:

val bar : bool option = None 
val baz : bool option = Some true

请注意,您可以使用您找到的辅助函数,但您也需要一个用于op_Implicit调用的函数。

使用转换器功能,这变得更干净了。我已经修改了上面的代码以使用(稍微修改的版本)您的转换器帮助程序:

let inline convi (x : ^a) : ^b = ((^a or ^b) : (static member op_Implicit : ^a -> ^b) x)
let inline conve (x : ^a) : ^b = ((^a or ^b) : (static member op_Explicit : ^a -> ^b) x)

let xe = XElement.Parse("<foo><baz>true</baz></foo>")
let elementToBool e =
  match e with
    | null -> None
    | e -> Some(conve e : bool)

let baz = "baz" |> convi |> xe.Element |> elementToBool
let bar = "bar" |> convi |> xe.Element |> elementToBool
于 2013-11-13T23:13:50.237 回答