c# – F#struct构造函数中的参数验证

这是一个简单的C#结构,它对ctor参数进行了一些验证:
public struct Foo
{
    public string Name { get; private set; }

    public Foo(string name)
        : this()
    {
        Contract.Requires<ArgumentException>(name.StartsWith("A"));
        Name = name;
    }
}

我设法将其翻译成F#类:

type Foo(name : string) = 
    do 
        Contract.Requires<ArgumentException> (name.StartsWith "A")
    member x.Name = name

但是,我无法将其转换为F#中的结构:

[<Struct>]
type Foo = 
    val Name : string
    new(name : string) = { do Contract.Requires<ArgumentException> (name.StartsWith "A"); Name = name }

这给编译错误

Invalid record,sequence or computation expression. Sequence expressions should be of
the form ‘seq { … }’

This is not a valid object construction expression. Explicit object constructors must
either call an alternate constructor or initialize all fields of the object and specify
a call to a super class constructor.

我已经看过thisthis,但是它们并没有涵盖参数验证.

我在哪里做错了?

解决方法

您可以在初始化结构体之后使用block.它在您的第一个 link中的类中描述为在构造函数中执行副作用,但它也适用于结构体.
[<Struct>]
type Foo = 
    val Name : string
    new(name : string) = { Name = name } 
                         then if name.StartsWith("A") then failwith "Haiz"

更新:

更接近你的例子的另一种方法是使用; (顺序组合)和括号组合表达式:

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

相关文章

在要实现单例模式的类当中添加如下代码:实例化的时候:frmC...
1、如果制作圆角窗体,窗体先继承DOTNETBAR的:public parti...
根据网上资料,自己很粗略的实现了一个winform搜索提示,但是...
近期在做DSOFramer这个控件,打算自己弄一个自定义控件来封装...
今天玩了一把WMI,查询了一下电脑的硬件信息,感觉很多代码都...
最近在研究WinWordControl这个控件,因为上级要求在系统里,...