Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/fsharp/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Generics 根据类型选择BitConverter.ToXXX函数_Generics_F#_Higher Order Functions - Fatal编程技术网

Generics 根据类型选择BitConverter.ToXXX函数

Generics 根据类型选择BitConverter.ToXXX函数,generics,f#,higher-order-functions,Generics,F#,Higher Order Functions,我通常试图使我的问题更一般化,但这次我认为示例案例使问题更清楚。我也是F#的新手,所以在现阶段尝试过多的概括可能是一个错误:) 我想要实现的是创建一个函数,为给定的类型参数返回相应的BitConverter.ToXXX函数。以下是我尝试过的: let FromBytes<'a> : (byte[] * int -> 'a) = match typeof<'a> with | x when x = typeof<Int16> -> BitC

我通常试图使我的问题更一般化,但这次我认为示例案例使问题更清楚。我也是F#的新手,所以在现阶段尝试过多的概括可能是一个错误:)

我想要实现的是创建一个函数,为给定的类型参数返回相应的
BitConverter.ToXXX
函数。以下是我尝试过的:

let FromBytes<'a> : (byte[] * int -> 'a) = 
  match typeof<'a> with
  | x when x = typeof<Int16> -> BitConverter.ToInt16
  | x when x = typeof<UInt16> -> BitConverter.ToUInt16
  | _ -> failwith "Unknown type"

let FromBytes您需要强制转换最终值:

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"

let FromBytes您需要强制转换最终值:

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"

let FromBytes+1,因为这非常有用/有教育意义,但您确实更改了函数签名:)。但我想知道为什么。通过对象进行强制转换似乎也适用于我原来问题中的函数。。。i、 e.
box BitConverter.ToInt16:?>(字节[]*int->'a)
。另外,我对您提到的编译时解决方案也很感兴趣。签名是等效的,但也可以像最初一样省略参数,请参阅更新版本。这现在是FsControl:+1的一部分,因为这非常有用/有教育意义,但您确实更改了函数签名:)。但我想知道为什么。通过对象进行强制转换似乎也适用于我原来问题中的函数。。。i、 e.
box BitConverter.ToInt16:?>(字节[]*int->'a)
。另外,我对您提到的编译时解决方案也很感兴趣。签名是等效的,但也可以像最初一样省略参数,请参阅更新版本。这现在是FsControl的一部分: