F#独特的过载方法

时间:2010-11-08 07:55:24

标签: generics f# types

我怎么能在这种类型中调用send(a:'T [])?

type Test() =
  member o.send(value:'T) = 4
  member o.send(values:'T []) = 5

let test = Test()
let b = test.send [|4|]

当我这样做时,我获得了

A unique overload for method 'Send' could not be determined based on type information 
prior to this program point. The available overloads are shown below...

关键是MPI.NET正好有这个名为Send的方法,我无法向其中发送数组。

谢谢你,
Oldrich

3 个答案:

答案 0 :(得分:2)

好吧,F#无法确定你的T是int还是int数组,所以我能看到解决问题的唯一方法是这样的

let b = test.send<int> [|4|]

或者

let b = test.send<int array> [|4|]

答案 1 :(得分:2)

type Test() =
  member o.send(a:'T) = 4
  member o.send(a:'T []) = 5

let test = Test()
let b = test.send<int>([|4|] : _[]) // 5

答案 2 :(得分:0)

您可以通过在类型上使用模式匹配来完成此操作:

type MyTest() =
    member this.Send (a : obj)  = 
        match a with
        | :? System.Collections.IEnumerable -> 5
        | _ -> 4

这将匹配F#(array,list,seq)中的任何Seq类型。一旦你有正确的匹配,通常更容易实现特定类型的私有函数。