LINQ to XML 中的 F# 和显式转换

标签 f# linq-to-xml operator-keyword xelement explicit-conversion

在 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))

最佳答案

不幸的是,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

关于LINQ to XML 中的 F# 和显式转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19965947/

相关文章:

c# - 控制台应用程序中的 Application.Current "null"

f# - Seq.find 返回 'a -> int 而不是 int

f# - 为什么 FSharp.Data.SqlClient 记录作为对象公开?

C# XML X文档

c++ - 如何修复 : binary = :no operator exists which takes a RHS of const & fullName

asynchronous - 使用 F# 样式的异步工作流的 WebRequest 超时

c# - 不使用 for 循环创建 XmlDocument

c# - 我的 LINQ 查询仅返回 1 个结果

java - 错误: bad operand types for binary operator '=='

c++ - 在 C++ 函数中通过引用返回的目的是什么?