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



我试着用f#写一个简单的抽象类,带有一些基本的参数验证:

[<AbstractClass>]
type Record(recordType: int16) =
let recordType: int16 = recordType
do
if recordType < 0s then
invalidArg (nameof recordType)

然而,我在最后一行得到一个错误:'这个if表达式缺少一个else分支。'我试着添加一个else分支,只是评估为null,但是类型系统不同意我的代码。我做错了什么吗?我应该使用其他方法验证我的参数吗?

问题是invalidArg需要一个参数名称(你已经传递了nameof recordType以及一个错误消息,你离开了,你的if分支返回一个函数(string -> 'a作为返回类型是未知的/不可达的,因为异常被抛出)。

如果您查看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"

最新更新