简体   繁体   English

复制对象而不保留参考

[英]Copying objects without keeping a reference

Background: I have a list of objects that are directly linked to the UI in WPF. 背景:我有一个直接链接到WPF中的UI的对象列表。 I need to do some work with those objects, but while I am working with them (asynchronously) I do not want any refreshes on the UI (performance and aesthetic reasons). 我需要对那些对象做一些工作,但是当我(异步)使用它们时,我不希望UI发生任何刷新(性能和美观方面的原因)。

So I thought, I might copy the items (using Collection<T>.CopyTo(T[] array, int index) ), work on the copy, then override my original list with the copied one. 所以我想,我可以复制项目(使用Collection<T>.CopyTo(T[] array, int index) ),在副本上进行处理,然后用复制的副本覆盖原始列表。 The problem is, that even then the reference are kept and the UI is continuously refreshed. 问题是,即使这样,引用仍会保留,并且UI会不断刷新。 Code example of what I did: 我所做的代码示例:

    MyUIObject[] myCopiedList = new MyUIObject[MyObjectsLinkedToTheUI.Count];
    MyObjectsLinkedToTheUI.CopyTo(myCopiedList);
    foreach (MyUIObject myCopiedItem in myCopiedList)
    {
        //while I do this, the UI is still updated
        PerformLongAndWearyOperationAsync(myCopiedItem);
    }
    MyObjectsLinkedToTheUI.Clear();
    foreach (var myCopiedItem in myCopiedList)
    {
        MyObjectsLinkedToTheUI.Add(myCopiedItem);
    }

Is there a possibility to copy my items without keeping a reference to the original object? 是否可以在不保留原始对象引用的情况下复制我的物品?

UPDATE 1 更新1

Thank you for your contributions so far. 谢谢您到目前为止的贡献。 One thing I forgot to mention: This is for Windows Phone 8.1, so ICloneable is not available. 我忘记提及的一件事:这是用于Windows Phone 8.1的,因此ICloneable不可用。

You need to clone them somehow. 您需要以某种方式克隆它们。 Either implement ICloneable interface and do all rewriting manually or you can use some hacks/tricks like serializing and deserializing object. 要么实现ICloneable接口并手动进行所有重写,要么可以使用一些技巧/技巧,例如对对象进行序列化和反序列化。

Flow with serialization is something like this: 序列化流程是这样的:

  1. Take your object 带上你的东西
  2. Serialize it to, for example, JSON, binnary format etc. 将其序列化为例如JSON,二进制格式等。
  3. Now deserialize what you got in step 2 into new object 现在将第二步中获得的结果反序列化为新对象

You'll have a copy of your object that way but it costs more processing power and is prone to some hard to catch errors. 您将以这种方式获得对象的副本,但是它将花费更多的处理能力,并且容易出现一些难以捕捉的错误。 But it's an easy way to go. 但这是一个简单的方法。 Thing with implementing ICloneable is more reliable but you need to write all that mapping by yourself. 实现ICloneable的方法更可靠,但是您需要自己编写所有映射。

Also, consider using structs instead of classes. 另外,请考虑使用结构而不是类。 Structs are always copied by value not reference. 结构总是按值复制,而不是引用。 It has some drawbacks so it's up to you if they suit your usage scenario. 它有一些缺点,所以如果它们适合您的使用情况,则取决于您。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM