我有一段声明可变字典的代码,但当我尝试更改其中一个元素时会出错。
代码如下:
let layers =
seq {
if recipes.ContainsKey(PositionSide.Short) then yield! buildLayerSide recipes.[PositionSide.Short]
if recipes.ContainsKey(PositionSide.Long) then yield! buildLayerSide recipes.[PositionSide.Long]
}
|> Seq.map (fun l -> l.Id, l)
|> dict
这里创建了一个 IDictionary
。我理解对象本身是不可变的,但字典的内容应该是可变的。
当我通过显式初始化字典来更改代码时,它就变成可变的:
let layers =
let a =
seq {
if recipes.ContainsKey(PositionSide.Short) then yield! buildLayerSide recipes.[PositionSide.Short]
if recipes.ContainsKey(PositionSide.Long) then yield! buildLayerSide recipes.[PositionSide.Long]
}
|> Seq.map (fun l -> l.Id, l)
|> dict
let x = Dictionary<string, Layer>()
a
|> Seq.iter (fun kvp -> x.[kvp.Key] <- kvp.Value)
x
为什么会这样呢?
Dictionary
和IDictionary
。 - Fyodor Soikin