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

时间:2009-11-06 18:29:51

标签: .net f# functional-programming constructor

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

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

1 个答案:

答案 0 :(得分: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    

这是执行此操作的典型方法。让“最具参数”的构造函数成为隐式构造函数,并将其余部分定义为调用隐式构造函数的类中的成员。

修改

Beta2中有关于抽象类的错误。在某些情况下,您可以使用隐式构造函数的默认参数来解决它,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