问题描述
我只是提供部分代码...在代码beloe中,当它到达messageHolder.To="!"
时,它还会更改k.tmp.To
的值
谁能告诉我为什么会这样以及如何解决这个问题?我需要k.tmp.To
的值保持不变.
I''m just providing the partial code... In the code beloe when it reaches messageHolder.To="!"
, It also changes the value of k.tmp.To
Can anyone tell me why is this happening and how to remove this problem? I need the value of k.tmp.To
to remain the same.
for (int i = 0; i < sharedData.pendingList.Count; i++)
{
k = (sharedData.pendingMessages)sharedData.pendingList[i];
if (k.tmp.To.StartsWith("@") || k.tmp.To.StartsWith("#"))
{
gpName = k.tmp.To.Substring(1); // the gpName without the @
gpUserList = dbConn.getUserFromGroup(gpName);
CommonsCF.Data messageHolder = new CommonsCF.Data();
for (int i2 = 0; i2 < gpUserList.Count; i2++)
{
messageHolder = k.tmp;
MessageBox.Show("Starts1: " + k.tmp.To.StartsWith("#").ToString());
if (k.tmp.To.StartsWith("#"))
{
messageHolder.To = "!";
[修改:通常,在我们看到代码之前,我们喜欢看问题,以便我们知道我们是否可以提供帮助.首先看代码有时会使人们不去看它.此外,整理粘贴(例如,删除多余的空格)仅需花费几秒钟的时间,就可以使代码更容易阅读.]
[Modified: generally, before we see code, we like to see the question so that we know if we think we can help. Seeing code first can sometimes get people to not look at it. Also, just a few extra seconds of tidying up your pasting (ie. removing extra spaces) can make the code a lot easier to read]
推荐答案
CommonsCF.Data messageHolder = new CommonsCF.Data();
messageHolder = k.tmp;
messageHolder.To = "!";
我已将您的代码缩减以显示重要的行.
messageHolder是对CommonsCF.Data类实例的引用,因此ID为k.tmp.
当您将k.tmp分配给messageHolder时,它不会复制内容-它会复制引用.因此,当您修改messageHolder时,您还同时在修改k.tmp,因为它们都引用同一个实例.
就像手机一样,您可以将SIM卡从手机中取出,然后放入新手机中-该号码随SIM卡一起移动,因此当您拨打旧号码时,新电话会响铃.
I have cut your code down to show the important lines.
messageHolder is a reference to a CommonsCF.Data class instance, so id k.tmp.
When you assign k.tmp to messageHolder, it does not copy the content - it copies the reference. So when you modify messageHolder, you are also modifying k.tmp as they are both referring to the same instance.
It''s a bit like a mobile, you can take the SIM out of yours and put it in a new phone - the number moves with the SIM so the new phone rings when you call the old number.
这篇关于在循环中更改1个变量也会更改其他变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!