在F#中.是否可以重载抽象类型的构造函数?

Ene*_*nes 5 .net f# constructor functional-programming

如果是,你可以给出一个带无参数和"parameterfull"构造函数的类型的例子.

这是你建议使用的东西还是F#提供了一些替代的更多功能方式.如果是的话,请举一个例子吗?

Bri*_*ian 2

像这样?

type MyType(x:int, s:string) =
    public new() = MyType(42,"forty-two")
    member this.X = x
    member this.S = s

let foo = new MyType(1,"one")
let bar = new MyType()
printfn "%d %s" foo.X foo.S    
printfn "%d %s" bar.X bar.S    
Run Code Online (Sandbox Code Playgroud)

这是典型的做法。让“参数最多”的构造函数成为隐式构造函数,并将其余的“新”重载定义为调用隐式构造函数的类中的成员。

编辑

Beta2 中存在一个关于抽象类的错误。在某些情况下,您可以使用隐式构造函数上的默认参数来解决它,例如

[<AbstractClass>]
type MyType(?cx:int, ?cs:string) =
    let x = defaultArg cx 42
    let s = defaultArg cs "forty-two"
    member this.X = x
    member this.S = s
    abstract member Foo : int -> int

type YourType(x,s) =
    inherit MyType(x,s)    
    override this.Foo z = z + 1

type TheirType() =
    inherit MyType()    
    override this.Foo z = z + 1

let foo = new YourType(1,"one")
let bar = new TheirType()
printfn "%d %s" foo.X foo.S    
printfn "%d %s" bar.X bar.S    
Run Code Online (Sandbox Code Playgroud)