英文:
Why does ImmutableDictionary.GetValueOrDefault return null here?
问题
这里有使用 ImmutableDictionary 的一些代码:
打开 System.Collections.Immutable
let dict = ImmutableDictionary.Create()
let key = "abc"
dict = dict.Add(key, "xyz")
dict.GetValueOrDefault(key)
|> printfn "%A"
输出是 <null>。
为什么不是 "xyz"?
英文:
Here is some code using ImmutableDictionary:
open System.Collections.Immutable
let dict = ImmutableDictionary.Create()
let key = "abc"
dict = dict.Add(key, "xyz")
dict.GetValueOrDefault(key)
|> printfn "%A"
The output is <null>.
Why is it not "xyz"?
答案1
得分: 2
The = below is not an assignment:
dict = dict.Add(key, "XYZ")
but an equality check: this check results in false, and that value is discarded.
dict is an immutable dictionary, and dict.Add(key, "XYZ") returns a new dictionary that has the newly added entry. So, you can instead mark the value dict as mutable and use the assignment (<-) to assign it the new resulting dictionary:
open System.Collections.Immutable
let mutable dict = ImmutableDictionary.Create()
let key = "abc"
dict <- dict.Add(key, "xyz")
dict.GetValueOrDefault(key)
|> printfn "%A"
The output now is "xyz".
英文:
The = below is not an assignment:
dict = dict.Add(key, "XYZ")
but an equality check: this check results in false, and that value is discarded.
dict is an immutable dictionary, and dict.Add(key, "XYZ") returns a new dictionary that has the newly added entry. So, you can instead mark the value dict as mutable and use the assignment (<-) to assign it the new resulting dictionary:
open System.Collections.Immutable
let mutable dict = ImmutableDictionary.Create()
let key = "abc"
dict <- dict.Add(key, "xyz")
dict.GetValueOrDefault(key)
|> printfn "%A"
The output now is "xyz".
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论