这段代码不起作用,因为我把选项和可选参数弄混了。
如何将选项传递给可选参数?
type Foo() =
member this.Bar(?name : string, ?number : int) =
let name = defaultArg name "johndoe"
let number = defaultArg number 0
name + "-" + string number
[<AutoOpen>]
module FooExtensions =
open System
type Foo with
member this.Bar(?name : string, ?numberAsString : string) =
let number =
numberAsString
|> Option.map Int32.Parse
this.Bar(name=name, number=number) // Invalid
您可以在调用方法时将问号前缀放在命名参数上,以表明您希望将值作为option
传递。
this.Bar(?name=name, ?number=number)