2009-11-06 53 views

回答

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中有一個關於抽象類的bug。在某些情況下,你可以解決它使用默認參數的隱式構造,一拉

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

肯定的,但它必須是一個抽象類型 – Enes 2009-11-06 18:42:38

+0

哇,你是對的,使其成爲抽象類,它不起作用。這是一個錯誤;我已經提交了。感謝您提出這個問題! – Brian 2009-11-06 19:41:55

+0

很棒....不是真的,但謝謝你的答案。在此期間是否有解決方法來實現這一目標?我的意思是讓課堂不是抽象的。 – Enes 2009-11-06 19:45:58

相關問題