gpt4 book ai didi

class - 使用 F# 在显式对象构造函数中失败

转载 作者:行者123 更新时间:2023-12-05 01:37:04 25 4
gpt4 key购买 nike

下面的代码

type A (b) =
new () =
if true then A 4.
else failwith ""

报错:

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.

这个有效:

type A (b) =
new () =
if true then A 4.
else failwith ""; A 4.

简单的问题。构造函数中的 failwith 有什么不好?

最佳答案

问题不是 failwith 本身。如错误所示,非主构造函数受到限制。这是为了鼓励将所有初始化逻辑放在主构造函数中。你的例子似乎是人为的。如果您展示更多您正在尝试做的事情,也许有人可以提供解决方案。

这是一种重新编写代码的方法:

type A (b) =
new () = A(4.0) then
if true then failwith ""

then 在非主构造函数中的作用类似于 do 绑定(bind)。

请参阅 Constructors 上的 MSDN 页面更多选项。

编辑

kvb 就具有副作用的主构造函数提出了一个很好的观点。如果是这种情况,您可能需要考虑将逻辑移至静态方法。这使得在调用构造函数之前可以完成其他工作变得显而易见。

type A (b) =
static member Create() =
if true then failwith ""
else A(4.0)

关于class - 使用 F# 在显式对象构造函数中失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7597338/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com