加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 06:49:25 所属栏目:百科 来源:网络整理
导读:这是一个简单的C#结构,它对ctor参数进行了一些验证: public struct Foo{ public string Name { get; private set; } public Foo(string name) : this() { Contract.RequiresArgumentException(name.StartsWith("A")); Name = name; }} 我设法将其翻译成F#类
这是一个简单的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.

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

我在哪里做错了?

解决方法

您可以在初始化结构体之后使用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) }

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读