本文介绍了使用替代类语法在构造函数中添加代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

type Foo = 
    class
        inherit Bar

        val _stuff : int

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

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

I want to add this code in above constructor:

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

我该如何在F#中实现此目标?

How can I achieve this in F# ?

推荐答案

您可以执行此操作,而无需任何变通方法,但是初始左卷曲的位置非常敏感(或者解析器有错误?)。首先要做效果:

You can do this without needing any workarounds, but the placement of the initial left curly is fairly sensitive (or maybe the parser is buggy?). To do the effect first:

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

这篇关于使用替代类语法在构造函数中添加代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-03 03:16