ImmutableDictionary.GetValueOrDefault在这里为什么返回null?

huangapple go评论53阅读模式
英文:

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 = &quot;abc&quot;

dict = dict.Add(key, &quot;xyz&quot;)

dict.GetValueOrDefault(key) 
|&gt; printfn &quot;%A&quot;

The output is &lt;null&gt;.

Why is it not &quot;xyz&quot;?

答案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, &quot;XYZ&quot;)

but an equality check: this check results in false, and that value is discarded.


dict is an immutable dictionary, and dict.Add(key, &quot;XYZ&quot;) returns a new dictionary that has the newly added entry. So, you can instead mark the value dict as mutable and use the assignment (&lt;-) to assign it the new resulting dictionary:

open System.Collections.Immutable

let mutable dict = ImmutableDictionary.Create()

let key = &quot;abc&quot;

dict &lt;- dict.Add(key, &quot;xyz&quot;)

dict.GetValueOrDefault(key) 
|&gt; printfn &quot;%A&quot;

The output now is &quot;xyz&quot;.

huangapple
  • 本文由 发表于 2023年6月5日 02:02:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/76401776.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定