【问题标题】:ContainsKey returns unit and not bool?ContainsKey 返回单位而不是布尔值?
【发布时间】:2017-12-05 16:32:01
【问题描述】:

以下代码引发编译时错误对我来说很奇怪。我不确定为什么 ContainsKey 会返回单位。 documentation 表示它返回 bool。

open System.Collections.Generic    

let mydict = new Dictionary<string,'a>()

if(mydict.ContainsKey "mykey") then
    mydict.["mykey"] = newkey

错误 FS0001:此表达式应具有类型 'bool' 但这里有类型 '单位'

我错过了什么吗?

【问题讨论】:

  • 返回 bool 的不是 ContainsKey。下一行是比较运算符=

标签: f#


【解决方案1】:

if 是一个表达式,因此两个分支必须具有相同的类型。如果未指定else 分支,则插入unit 类型的空分支。这意味着您的then 分支也必须具有unit 类型。但是mydict.["mykey"] = newkey 的类型为bool。如果你想为mykey 插入一个新值,你应该使用&lt;- 而不是=

if(mydict.ContainsKey "mykey") then
    mydict.["mykey"] <- newkey

【讨论】:

    猜你喜欢
    • 2017-04-22
    • 2020-02-13
    • 2015-02-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-03
    • 2012-08-08
    相关资源
    最近更新 更多