这是一个简单的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.
我在哪里做错了?
解决方法
您可以在初始化结构体之后使用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) }