首页 文章

抽象类类型签名中的可选参数

提问于
浏览
5

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 回答

  • 2

    将参数声明为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
    
  • 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
    
  • 8

    这应该工作:

    [<AbstractClass>]
    type AbstractExample () = 
        abstract WithOptionalParameters: int * Nullable<int> -> unit
    

    In F#, there's no syntactical sugar for nullable types,因此虽然您可以使用 ?y 语法声明一个可为空的值,但您不能对类型执行此操作 . 相反,你将不得不使用 Nullable<T> .

相关问题