班级:
type NotAbstract () =
member this.WithOptionalParameters (x, ?y) =
let y = defaultArg y 10
x + y
具有以下类型签名:
type NotAbstract =
class
new : unit -> NotAbstract
member WithOptionalParameters : x:int * ?y:int -> int
end
然而,这不起作用:
[<AbstractClass>]
type AbstractExample () =
abstract WithOptionalParameters: int * ?int -> int /// Ouch...
type NotAbstract () =
inherit AbstractExample ()
override this.WithOptionalParameters (x, ?y) =
let y = defaultArg y 10
x + y
如何在带有可选参数的函数的抽象定义中编写正确的类型签名?我没有找到任何提示here。
PS:我知道polymorphism
可以实现(类似的)结果答案 0 :(得分:8)
将参数声明为Option类型并不会使参数成为可选参数。
NotAbstract().WithOptionalParameters(2)
// This expression was expected to have type
// int * Option<int>
// but here has type
// int
spec §8.13.6有它:
在签名中,可选参数如下所示:
static member OneNormalTwoOptional : arg1:int * ?arg2:int * ?arg3:int -> int
在抽象成员签名中命名可选参数
[<AbstractClass>]
type AbstractExample () =
abstract WithOptionalParameters: int * ?y:int -> int
type NotAbstract () =
inherit AbstractExample ()
override this.WithOptionalParameters (x, ?y) =
let y = defaultArg y 10
x + y
NotAbstract().WithOptionalParameters(42) // val it : int = 52
答案 1 :(得分:4)
可选参数编译为Option
类型,使用Option<int>
代替?int
:
[<AbstractClass>]
type AbstractExample () =
abstract WithOptionalParameters: int * Option<int> -> int
type NotAbstract () =
inherit AbstractExample ()
override this.WithOptionalParameters (x, ?y) =
let y = defaultArg y 10
x + y
答案 2 :(得分:2)
这应该有效:
[<AbstractClass>]
type AbstractExample () =
abstract WithOptionalParameters: int * Nullable<int> -> unit
In F#, there's no syntactical sugar for nullable types,因此虽然您可以使用?y
语法声明值为空,但您不能为类型执行此操作。相反,您必须使用Nullable<T>
。