微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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) }

原文地址:https://www.jb51.cc/csharp/94506.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐