如何在F#中区分联合的匹配

Whi*_*eyJ 4 selenium f#

如何获取返回对象的函数的结果,并将其转换为F#中的区分联合?

问题场景,我正在使用selenium中的webdriver上的javascript执行器.文档指定输出应该是certian类型的对象或类型列表.(参考https://www.w3.org/TR/webdriver/#executing-script)

我想通过将它转换成一个有区别的联合来给返回的对象一些结构,以便我可以在以后匹配它.

直接转换不起作用,并且不允许联合类型具有构造函数,因此我也不能完全删除它.解决这个问题的正确方法是什么?

type JsResult = 
    | E of IWebElement
    | I of Int64
    | B of bool
    | S of String
    | LE of IWebElement list
    | LI of Int64 list
    | LB of bool list
    | LS of String list
    | N of Object
    override self.ToString () =
        match self with 
        | E e -> e.Text
        | I i -> i.ToString()
        | B b -> b.ToString() 
        | S s -> s
        | LE le -> String.concat " " (le |> Seq.map(fun x-> x.Text))
        | LI li -> String.concat " " (li |> Seq.map(fun x-> x.ToString()))
        | LB lb -> String.concat " " (lb |> Seq.map(fun x-> x.ToString()))
        | LS ls -> String.concat " " ls
        | N _ -> String.Empty

let execute script : JsResult = (browser :?> IJavaScriptExecutor).ExecuteScript(script) :> JsResult
Run Code Online (Sandbox Code Playgroud)

mon*_*res 6

也许创建一个静态工厂方法?试试这个:

type JsResult = 

    // ...

    with static member ofObject o =
        match box o with
        | :? IWebElement as e -> E e
        | :? Int64 as i -> I i
        | :? bool as b -> B b
        | :? String as s -> S s
        | :? (IWebElement list) as le -> LE le
        | :? (Int64 list) as li -> LI li
        | :? (bool list) as lb -> LB lb
        | :? (String list) as ls -> LS ls
        | :? Object as n -> N o
        | _ -> failwith "No wrapper available for type"


let execute script : JsResult = (browser :?> IJavaScriptExecutor).ExecuteScript(script) |> JsResult.ofObject
Run Code Online (Sandbox Code Playgroud)

(仅当任何指定类型是类型为int或bool的值时才需要装箱).