2011-03-15 116 views
3

我想要一個空構造函數和一個接受參數並將其分配給公共屬性的構造函數重載。f#中帶有屬性賦值的多個構造函數

這是我堅持:

type TemplateService() = 
    interface ITemplateService with 

     //Properties 
     member TemplateDirectory = "" 

     //Constructors 
     new (templateDirectory:string) = //Error here. 
      if (templateDirectory == null) then 
       raise (new System.ArgumentNullException("templateDirectory")) 
      TemplateDirectory = templateDirectory; 

它給我的錯誤:在對象表達`意外的關鍵詞「新」。預期的「成員」,「覆蓋」或其他標記。

如果我使用member,物業TemplateDirectory給出了這樣的錯誤:

This instance member needs a parameter to represent the object being invoked. Make the member static or use the notation 'member x.Member(args) = ...'

回答

6

你可以試試這個。

type TemplateService(templateDirectory : string) = 
    do 
     if templateDirectory = null then nullArg "templateDirectory" 

    new() = TemplateService("") 

    interface ITemplateService with 
     member this.TemplateDirectory = templateDirectory 
+0

如果我想在分配前檢查'd'是空還是空,該怎麼辦?比如在它之前拋出一個錯誤。 – 2011-03-15 03:58:20

+0

請參閱Daniel編輯的版本進行空檢查。 – 2011-03-15 04:51:26

+0

但我只需要爲接受爭論的構造函數做這個測試。如果我做'新的TemplateService()',那麼它會拋出一個錯誤。 – 2011-03-15 05:04:14

0

不幸的是,如果你想使用接口並將值傳遞給構造函數nyinyithann答案是正確的。您可以像這樣在構造函數中設置公共屬性。

type TemplateService() = 
    let mutable templateDirectory = "" 

    member this.TemplateDirectory 
     with get() = templateDirectory 
     and set directory = 
      if directory = null then 
       raise (new System.ArgumentNullException "templateDirectory") 
      templateDirectory <- directory 

let template = TemplateService(TemplateDirectory = "root") 

現在,如果你想使用一個接口,這將無法正常工作。我們不得不使用這個醜陋的東西。

let template = TemplateService() 
(template :> ITemplateService).TemplateDirectory <- "root" 
+0

我的建議是,當你想要接口和普通訪問時,只需簡單地定義它兩次,一次在接口之外,並在接口中包裝。 – Guvante 2011-03-15 19:24:55

0

你把在接口的定義構造函數,這是錯誤的原因。此外,您正嘗試將值存儲到僅獲取屬性,而應該使用後備存儲。

最後,我會推薦nyinyithann的版本,因爲它與通常的F#風格(最小可變)更直接,只是希望給一個更接近你的版本,以防萬一它有幫助。

type TemplateService() = 
    let mutable directory = "" 

    interface ITemplateService with 

     //Properties 
     member this.TemplateDirectory = directory 

    //Constructors 
    new (templateDirectory:string) = 
     if (templateDirectory = null) then 
      raise (new System.ArgumentNullException("templateDirectory")) 
     directory <- templateDirectory; 
相關問題