如何获取返回对象的函数的结果,并将其转换为 F# 中的可区分联合?
问题场景,我正在使用 selenium 中的 webdriver 上的 javascript 执行程序。文档指定输出应该是证书类型或类型列表的对象。 (引用 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
最佳答案
也许创建一个静态工厂方法?尝试这个:
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
(仅当任何指定类型是 int 或 bool 等值类型时才需要装箱)。
关于selenium - 如何折叠 F# 中受歧视联合的匹配项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41045778/