gpt4 book ai didi

f# - 动态转换为界面

转载 作者:行者123 更新时间:2023-12-04 06:53:00 25 4
gpt4 key购买 nike

根据帖子http://cs.hubfs.net/forums/thread/3616.aspx ,我需要使用类似下面的函数将对象转换为接口(interface),我已经运行了测试,仍然如此,:?> 的错误仍然没有修复。

let cast<'a> o = (box o) :?> 'a
let ci = { new Customer(18, Name = "fred") with
override x.ToString() = x.Name
interface ITalk with
member x.Talk() =
printfn "talk1111111" }

let italk = cast<ITalk> ci

if not (italk = null) then
italk.Talk()

上面的代码有没有更优雅的写法。我正在考虑创建另一个运算符来替换 :?>,但我无法像 :?>

那样获取传入的泛型类型参数

最佳答案

您的 cast 函数的行为不像 C# as 运算符 - 如果无法将对象转换为指定类型,它将抛出异常而不是返回无效的。因此,检查 italk = null 是否无济于事。如果你想让 cast 函数在转换失败时返回 null 而不是抛出异常,你可以这样写:

let cast<'a when 'a : null> o =
match box o with
| :? 'a as output -> output
| _ -> null

但是,这仅适用于可空类型,不包括结构或(默认情况下)F# 类型。我可能会按原样保留您的 cast 函数,并制作一个使用选项的 tryCast

let tryCast<'a> o =
match box o with
| :? 'a as output -> Some output
| _ -> None

然后你可以像这样使用它:

ci |> tryCast<ITalk> |> Option.iter (fun it -> it.Talk())

在这种情况下,Option.iter 将取代您的空测试。

关于f# - 动态转换为界面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6667547/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com