如何获取返回对象的函数的结果,并将其强制转换为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
答案 0 :(得分: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
(仅当任何指定类型是int类型或bool类型的值时才需要装箱。)