2009-11-17 129 views
2
type Foo = 
    class 
     inherit Bar 

     val _stuff : int 

     new (stuff : int) = { 
      inherit Bar() 
      _stuff = stuff 
     } 
    end 

我想在上面的構造函數添加以下代碼:添加代碼,構造函數替代類語法

if (stuff < 0) then raise (ArgumentOutOfRangeException "Stuff must be positive.") 
else() 

我如何在F#中實現這一目標?

回答

5

你可以做到這一點,而無需任何變通辦法,但最初的左花的位置是相當敏感(或者解析器是越野車? )。要做到效果第一:

type Foo = 
    class 
    inherit Bar 
    val _stuff : int 
    new (stuff : int) = 
     if stuff < 0 then raise (System.ArgumentOutOfRangeException("Stuff must be positive")) 
     { 
     inherit Bar() 
     _stuff = stuff 
     } 
    end 

做的效果第二:

type Foo = 
    class 
    inherit Bar 
    val _stuff : int 
    new (stuff : int) = 
     { 
     inherit Bar() 
     _stuff = stuff 
     } 
     then if stuff < 0 then raise (System.ArgumentOutOfRangeException("Stuff must be positive")) 
    end 
+0

整潔,良好的通話。 – Brian 2009-11-17 02:36:42

+0

謝謝!它只是工作。大括號的放置確實是挑剔的。 – Stringer 2009-11-17 20:39:44

3

嗯,看起來像一個語法漏洞;我會提出一個建議。你可以解決它是這樣的:

type Bar() = class end 

type Foo =  
    class   
     inherit Bar   
     val _stuff : int   
     private new (stuff : int, dummyUnused : int) = {    
      inherit Bar()    
      _stuff = stuff   
      } 
     new (stuff : int) = 
      Foo(stuff, 0) 
      then 
       if (stuff < 0) then 
        raise (System.ArgumentOutOfRangeException 
          "Stuff must be positive.") 
    end 

其中第一個構造函數是一個虛擬的,其唯一目的就是讓第二實構造與稱它爲「其他構造函數,然後副作用」語法。

但是如果你使用

type Foo(_stuff:int) =  
    inherit Bar() 
    do 
     if (_stuff < 0) then 
      raise (System.ArgumentOutOfRangeException "Stuff must be positive.") 

,而不是你會活得更長,更幸福的生活。 儘可能在主構造函數中使用類。('主構造函數'是類聲明的構造函數 - 在上例中,緊接在「type Foo」之後的參數是構造函數參數,並且類體內的任何let/do語句都定義了主構造函數體。

編輯:

這裏有一個更簡單的解決方法

type Foo =  
    class   
     inherit Bar   
     val _stuff : int   
     new (stuff : int) = 
      let effect = 
       if (stuff < 0) then 
        raise (System.ArgumentOutOfRangeException 
          "Stuff must be positive.") 
      {    
      inherit Bar()    
      _stuff = stuff   
      } 
    end 
+0

感謝。我知道主要ctor,在我的情況下我需要幾個ctors,所以唯一的方法就是class/end語法。 – Stringer 2009-11-17 20:42:07