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

     val _stuff : int 

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

내가 위의 생성자에서이 코드를 추가 할과 생성자 코드를 추가?대체 클래스 구문

답변

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

+0

감사! 그냥 작동합니다. 중괄호 배치는 실제로 까다 롭습니다. – Stringer

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가 필요하므로 갈 유일한 방법은 클래스/최종 구문입니다. – Stringer

관련 문제