F#中的反射和模式匹配

Ram*_*mbi 2 f#

我试图在给定F#中的Type时创建原始值.代码如下所示,但不起作用.我将非常感谢所有的帮助和感谢.

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))
Run Code Online (Sandbox Code Playgroud)

Dax*_*ohl 5

无需重新发明轮子,请使用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
Run Code Online (Sandbox Code Playgroud)