gpt4 book ai didi

f# - F# 中的反射和模式匹配

转载 作者:行者123 更新时间:2023-12-02 06:56:05 24 4
gpt4 key购买 nike

我正在尝试在给定 F# 类型的情况下创建原始值。代码如下所示,但不起作用。我将不胜感激所有帮助并提前致谢。

open System

let getvalue (t: Type) (v: string) : obj =
match box t with
| :? int -> let r = (int) v
box r
| :? byte -> let r = (byte) v
box r
| :? sbyte -> let r = (sbyte) v
box r
| :? int16 -> let r = (int16) v
box r
| :? uint32 -> let r = (uint32) v
box r
| :? int64 -> let r = (int64) v
box r
| :? uint64 -> let r = (uint64) v
box r
| :? double -> let r = (double) v
box r
| :? float32 -> let r = (float32) v
box r
| :? decimal -> let r = (decimal) v
box r
| :? char -> let r = (char) v
box r
| :? string -> v :> obj
| _ ->
let s = sprintf "Error unknown type %A" t
raise (ApplicationException(s))

最佳答案

无需重新发明轮子,使用Convert.ChangeType .

如果您愿意,可以围绕它编写一个包装器,让编译器自动确定类型。

let inline getValue<'a> (s:string) = // limit to string only if desired
System.Convert.ChangeType(s, typeof<'a>) :?> 'a

let x = getValue "1" + 1.2 // no need to explicitly state "float" anywhere here
printfn "%A" x // 2.2

关于f# - F# 中的反射和模式匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31152127/

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