您需要转换最终值:
let FromBytes<'a> : (byte[] * int -> 'a) =
match typeof<'a> with
| x when x = typeof<Int16> -> downcast (BitConverter.ToInt16 |> box)
| x when x = typeof<UInt16> -> downcast (BitConverter.ToUInt16 |> box)
| _ -> failwith "Unknown type"
这将在运行时检查类型并选择正确的大小写,在编译时使用静态约束也有一个技巧,但如果你正在学习它可能真的很混乱:
open System
type T = T with
static member ($) (T, _: int16) = fun v s -> BitConverter.ToInt16 (v,s)
static member ($) (T, _:uint16) = fun v s -> BitConverter.ToUInt16(v,s)
static member ($) (T, _: int ) = fun v s -> BitConverter.ToInt32 (v,s)
static member ($) (T, _:uint32) = fun v s -> BitConverter.ToUInt32(v,s)
let inline fromBytes (value:byte[], startIndex:int) =
(T $ Unchecked.defaultof< ^R>) value startIndex : ^R
// usage
let (x:int ) = fromBytes([|255uy;0uy;0uy;255uy|], 0)
let (y:uint16) = fromBytes([|255uy;0uy;0uy;255uy|], 0)
F# 编译器在调用站点内联所需的函数,您不能从 C# 调用泛型函数。