开发者

In F#. Is it possible to overload constructor of an abstract type?

If yes could you give an example of a type with parameterless and "parameterfull" constructor.

Is that something you would recommend using or does F# provide some alternative more functional way. If yes could you 开发者_JAVA技巧please give an example of it?


Like this?

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    

This is the typical way to do it. Have the 'most parameterful' constructor be the implicit constructor, and have the rest be 'new' overloads defined as members in the class that call into the implicit constructor.

EDIT

There is a bug in Beta2 regarding abstract classes. In some circumstances you can work around it using default arguments on the implicit constructor, a la

[<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    
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜