class :
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实现
3 回答
将参数声明为Option类型并不会使参数成为可选参数 .
spec §8.13.6有它:
因此,在抽象成员签名中命名可选参数
可选参数编译为
Option
类型,使用Option<int>
而不是?int
:这应该工作:
In F#, there's no syntactical sugar for nullable types,因此虽然您可以使用
?y
语法声明一个可为空的值,但您不能对类型执行此操作 . 相反,你将不得不使用Nullable<T>
.