Argument validation in F# struct constructor

烈酒焚心 提交于 2019-12-03 06:09:49

You can use then block after initializing structs. It is described for classes in your first link in section Executing Side Effects in Constructors, but it works for structs as well.

[<Struct>]
type Foo = 
    val Name : string
    new(name : string) = { Name = name } 
                         then if name.StartsWith("A") then failwith "Haiz"

UPDATE:

Another way closer to your example is to use ; (sequential composition) and parentheses to combine expressions:

[<Struct>]
type Foo = 
    val Name : string
    new(name : string) = 
        { Name = ((if name.StartsWith("A") then failwith "Haiz"); name) } 

If you want to avoid explicit fields (val) and then, two relatively esoteric features, you could use a static Create method and stick to the more common type definition syntax:

[<Struct>]
type Foo private (name: string) = 
  member x.Name = name
  static member Create(name: string) =
    Contract.Requires<ArgumentException> (name.StartsWith "A")
    Foo(name)
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!