gpt4 book ai didi

F# 此表达式的类型应为 'unit' ,但类型为 'bool'

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

我有以下代码

if somecondition then
myobj.Property1 = match myobj.Property1 with
| null -> SomePropertyType ()
| p -> p

我要做的是查看 myobj.Property1 是否为空,如果不是,则不要理会它,否则创建一个 SomePropertyType 类型的新对象并分配它。

问题是,我得到了一个

This expression should have type 'unit', but has type 'bool'

如果我必须在该 if 下放置多个 myobj.Property1 .... 语句,我该怎么办?

最佳答案

您正在比较两个值(使用 =),因此返回类型将为 bool , 但是如果你有一个 if 没有 else 编译器期望 unit作为返回类型。

我猜您打算将值分配给属性,请使用 <-而是:

if somecondition then
myobj.Property1 <- match myobj.Property1 with ...

无论如何,如果你想检查 null要分配默认值,您不需要 match , 一个 if then够了:

if somecondition then
if (myobj.Property1 = null) then myobj.Property1 <- SomePropertyType ()
...

更新

您可以“合并”两者 if .. then到单个 match :

match (somecondition, myobj.Property1) with
| true, null -> myobj.Property1 <- SomePropertyType ()
...

关于F# 此表达式的类型应为 'unit' ,但类型为 'bool',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24479497/

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