构造函数参数验证代码不编译

Constructor parameter validation code doesn't compile

我正在尝试用 F# 编写一个简单的摘要 class 并进行一些基本的参数验证:

[<AbstractClass>]
type Record(recordType: int16) =
    let recordType: int16 = recordType

    do
        if recordType < 0s then
            invalidArg (nameof recordType)

但是,我在最后一行遇到错误:'this if expression is missing an else branch.' 我尝试添加一个计算结果为 null 的 else 分支,但是类型系统与我的代码不一致。难道我做错了什么?我应该使用其他方法验证我的论点吗?

问题是 invalidArg 需要一个参数名称(您已将其作为 nameof recordType 传递,还有一条错误消息,您没有这样做,以及您的 if 分支 return 是一个函数(string -> 'a 因为 return 类型是 unknown/unreachable 因为抛出异常)。

如果您查看 docs for invalidArg,您会看到:invalidArg parameter-name error-message-string。您的代码实际上是这样的:

// This is a function: string -> 'a (as it raises an exception, the return type is unknown)
let partialInvalidArg = invalidArg (nameof recordType)
if recordType < 0s then
    partialInvalidArg // You're returning a function, not unit, so the compiler complains

如果包含错误消息,则该函数实际上是在分支中调用的,并且编译正常:

[<AbstractClass>]
type Record(recordType: int16) =
    let recordType: int16 = recordType

    do
        if recordType < 0s then
            invalidArg (nameof recordType) "The recordType must be greater or equal to zero"