一个物体的变化也会改变第二个物体 [英] A change in one object changes the second one too

查看:21
本文介绍了一个物体的变化也会改变第二个物体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建两个对象并为它们分配来自 IsolatedStorage 的数据.但是当我改变一个对象时,第二个对象也会改变.(我觉得问题可能是指针是一样的,但我解决不了.)

I'm creating two objects and assign them with a data from IsolatedStorage. But when I change one object the second one changes too. ( I think the problem may be the pointers are the same, but I can't solve it. )

private ArrayOfClsSimpleData lstUsers;
private ArrayOfClsSimpleData tmpLstUsers;

在课堂上的全局变量

tmpLstUsers = IsolatedStorageHelper.GetObject<ArrayOfClsSimpleData>("users");
lstUsers = IsolatedStorageHelper.GetObject<ArrayOfClsSimpleData>("users");

数组的第一个状态:

Debug.Write(lstUsers.Count)

输出: 2

Debug.Write(tmpLstUsers.Count)

输出: 2

计数与预期相同.但是,在我将一项添加到一个列表后,另一个列表也会更新并且计数仍然相同.

The counts are the same as expected. But, after I add an item to one list, the other list gets updated too and the counts are still same.

lstUsers.Add(new ArrayOfClsSimpleData());


Debug.Write(lstUsers.Count)

输出: 3

Debug.Write(tmpLstUsers.Count)

输出: 3

IsolatedStorageHelper 类是帮助获取对象、保存对象等的东西,我确实用它来简化事情,所以就认为它是从 IsolatedStorage 获取对象.

EDIT : IsolatedStorageHelper class is something to help to get objects, save object etc. that I do use for simplifying things, so just think it as getting objects from IsolatedStorage.

它是这样实现的:

 public static T GetObject<T>(string key)
    {
        if (IsolatedStorageSettings.ApplicationSettings.Contains(key))
        {
            return (T)IsolatedStorageSettings.ApplicationSettings[key];  // return the object 
        }

        return default(T); // if key doesn't exists , return default object
    }

所以它只是从 IndependentStorage 获取它.如果您不了解隔离存储,您可以从 这里

So it just gets it from IsolatedStorage. If you don't know isolated storage you can see it from here

那么,我该如何修复代码,以便我可以更改一个而不更改另一个?

So, how can I fix the code so that I can change one without changing the other?

推荐答案

所以,基本上 lstUserstmpLstUsers 是对同一个对象的引用.您所要做的就是创建一个新的并从原始内容复制内容.如果您需要快速解决方案,那么您可以这样做(代码如下).我只是猜测 ArrayOfClsSimpleData 是某种数组.

So, basically lstUsers and tmpLstUsers are references to the same object. All you have to do is to create a new one and copy content from the original. If you need a quick solution, then you can do it like this (code below). I just guess that ArrayOfClsSimpleData is some kind of array.

lstUsers = IsolatedStorageHelper.GetObject<ArrayOfClsSimpleData>("myKey");
tmpLstUsers = new ArrayOfClsSimpleData();

foreach (object user in lstUsers) // I don't know the type of objects in ArrayOfClsSimpleData, so I wrote 'object', but you should use the actual type
    tmpLstUsers.Add(user);

这篇关于一个物体的变化也会改变第二个物体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆