加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 23:14:12 所属栏目:百科 来源:网络整理
导读:在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)) 解决方法
在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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读