NoI*_*his 5 f# abstract-class optional-parameters
班级:
type NotAbstract () =
member this.WithOptionalParameters (x, ?y) =
let y = defaultArg y 10
x + y
Run Code Online (Sandbox Code Playgroud)
具有以下类型签名:
type NotAbstract =
class
new : unit -> NotAbstract
member WithOptionalParameters : x:int * ?y:int -> int
end
Run Code Online (Sandbox Code Playgroud)
但是,这不起作用:
[<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
Run Code Online (Sandbox Code Playgroud)
如何在带有可选参数的函数的抽象定义中编写正确的类型签名?我没有在这里找到任何暗示.
PS:我知道(类似的)结果可以通过多态实现
将参数声明为Option类型并不会使参数成为可选参数.
NotAbstract().WithOptionalParameters(2)
// This expression was expected to have type
// int * Option<int>
// but here has type
// int
Run Code Online (Sandbox Code Playgroud)
该规范§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
Run Code Online (Sandbox Code Playgroud)