使用替代类语法在构造函数中添加代码

Str*_*ger 2 syntax f# constructor

type Foo = 
    class
        inherit Bar

        val _stuff : int

        new (stuff : int) = {
            inherit Bar()
            _stuff = stuff
        }
    end
Run Code Online (Sandbox Code Playgroud)

我想在上面的构造函数中添加此代码:

if (stuff < 0) then raise (ArgumentOutOfRangeException "Stuff must be positive.")
else ()
Run Code Online (Sandbox Code Playgroud)

我怎样才能在F#中实现这一目标?

kvb*_*kvb 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
Run Code Online (Sandbox Code Playgroud)

要做到第二个效果:

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
Run Code Online (Sandbox Code Playgroud)