如何在F#中的约束中指定可选参数?

时间:2015-10-16 21:57:38

标签: f#

假设我有一个带有一些可选参数的方法,有没有办法通过一般约束来使用该方法?

我想做这样的事情:

type SomeClass() =
    member
        this.SomeMethod(?a:int, ?b:int) = 
            match a,b with
            | Some x, Some y -> x + y
            | _, _ -> 0
    member 
        this.SomeMethod (a:int,b:int) = a + b

// This doesn't work
let inline someMethod (a: ^T when ^T : (member SomeMethod: (?x:int)*(?y:int)->int)) = 
    (^T : (member SomeMethod: ?int*?int->int) (a,2,3))

let inline someMethod (a: ^T when ^T : (member SomeMethod2: int*int->int)) = 
    (^T : (member SomeMethod2: int*int->int) (a,2,3))

在F#中可以吗?

1 个答案:

答案 0 :(得分:3)

当然我马上就找到了答案,但这里的其他人也是如此:

type SomeClass() =
    member
        this.SomeMethod(?a:int, ?b:int) = 
            match a,b with
            | Some x, Some y -> x + y
            | _, _ -> 0
    member 
        this.SomeMethod (a:int,b:int) = a + b

let inline someMethod (a: ^T when ^T : (member SomeMethod: int option*int option->int)) = 
    (^T : (member SomeMethod: int option*int option->int) (a,Some 2,Some 3))

let inline someMethod2 (a: ^T when ^T : (member SomeMethod2: int*int->int)) = 
    (^T : (member SomeMethod2: int*int->int) (a,2,3))

let a = new SomeClass()
someMethod a