如何添加对象的副本而不是引用它
How to add a copy of an object instead of reference to it
所以 - 我在 F# 中添加了一个循环,其中包含一些复杂的逻辑,所以我使用 System.Collections.Generic.List 以便我可以在循环中添加它。
不过我发现的是,当我将一个项目添加到列表中时,它仍然以某种方式引用了该变量,因此当我更改“currentPostCodeRange”变量时,之前添加到列表中的所有内容也改变了!有没有一种方法可以以某种方式分配变量的“副本”,这样它就不会引用每一个项目..?
let postcodeRanges: System.Collections.Generic.List<Postcode.PostcodeRange>
= new System.Collections.Generic.List<Postcode.PostcodeRange>()
let mutable currentPostCodeRange: Postcode.PostcodeRange = { RangeType = Postcode.RangeType.Normal; From="0001"; To="0001" }
循环:
for postCode in 1 .. 9999 do
.....
if nextPostCodeisRural <> thisPostCodeisRural then
// this is the last one in this Range
currentPostCodeRange.To <- thisPostCodeString
postcodeRanges.Add(currentPostCodeRange)
.... etc, other logic
我认为在 F# 中复制记录的最简单方法是使用您在此处看到的 copy and update record expression. I strongly recommend against adding mutable objects to collections, though, precisely because it creates the aliasing 问题。但是,如果您决心这样做,您可以像这样添加一个副本:
postcodeRanges.Add({ currentPostCodeRange with To = currentPostCodeRange.To })
您必须在表达式中包含至少一个字段,因此在本例中,我明确复制了 To
字段,并隐式复制了其余字段。选哪一个都不重要。
再次强烈反对这种设计。我认为你最好使用 scan 或其他一些功能技术来长期 运行。
所以 - 我在 F# 中添加了一个循环,其中包含一些复杂的逻辑,所以我使用 System.Collections.Generic.List 以便我可以在循环中添加它。
不过我发现的是,当我将一个项目添加到列表中时,它仍然以某种方式引用了该变量,因此当我更改“currentPostCodeRange”变量时,之前添加到列表中的所有内容也改变了!有没有一种方法可以以某种方式分配变量的“副本”,这样它就不会引用每一个项目..?
let postcodeRanges: System.Collections.Generic.List<Postcode.PostcodeRange>
= new System.Collections.Generic.List<Postcode.PostcodeRange>()
let mutable currentPostCodeRange: Postcode.PostcodeRange = { RangeType = Postcode.RangeType.Normal; From="0001"; To="0001" }
循环:
for postCode in 1 .. 9999 do
.....
if nextPostCodeisRural <> thisPostCodeisRural then
// this is the last one in this Range
currentPostCodeRange.To <- thisPostCodeString
postcodeRanges.Add(currentPostCodeRange)
.... etc, other logic
我认为在 F# 中复制记录的最简单方法是使用您在此处看到的 copy and update record expression. I strongly recommend against adding mutable objects to collections, though, precisely because it creates the aliasing 问题。但是,如果您决心这样做,您可以像这样添加一个副本:
postcodeRanges.Add({ currentPostCodeRange with To = currentPostCodeRange.To })
您必须在表达式中包含至少一个字段,因此在本例中,我明确复制了 To
字段,并隐式复制了其余字段。选哪一个都不重要。
再次强烈反对这种设计。我认为你最好使用 scan 或其他一些功能技术来长期 运行。