变量的更改也会更改数组元素 [英] Changes in a variable also changing an array element

查看:101
本文介绍了变量的更改也会更改数组元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请让我直说吧!

Please could some one put me straight!

// I have a class:
public class Tuning
{
    public string Name;
    public string[] Notes = new string[6];
    public Tuning(Tuning tTuning)
   {
       Name = tTuning.Name;
       Notes = tTuning.Notes;
   }
   ... etc
}

// I have an array of them initialised with appropriate values:
public Tuning[] Tunings = new Tuning[6];

// I have a variable
public Tuning CurrentTuning = new Tuning(Tunings[x])

// I want to reverse the order of the variable''s contents
Array.Reverse(CurrentTuning.Notes)



为什么Tunings数组中的Notes值也相反?
而且,我该如何避免呢?
非常感谢



Why do the values of Notes in the Tunings array also reverse?
And, how can I avoid it?
Many thanks

推荐答案

它可能是因为它是浅表副本. CurrentTuning和Tunings指的是相同的内存位置.简而言之,它就像足球和橄榄球(不是美式橄榄球).两者都是同一游戏的不同名称.

如果希望它们是完全不同的对象,请从Tunings获取内存流,然后从中创建CurrentTunings. HTH
It''s probably because it is a shallow copy. CurrentTuning and Tunings refer to same memory location. Simply put, it''s like soccer and football (not American football). Both are different names for same game.

If you want them to be entirely different objects, get the memorystream from Tunings and then create CurrentTunings from it. HTH


值的更改Notes ,因为您在引用上执行的是shallow 副本而不是deep 副本. CurrentTuningNotes是不同的对象,它们指向数组的相同引用.为了避免这种行为,您需要一个深层副本.检查以下内容:> http:///stackoverflow.com/questions/129389/how-do-you-do-a-deep-copy-an-object-in-net-c专门 [ ^ ]
问候
Values of Notes change because you perform a shallow copy on reference instead of a deep copy. CurrentTuning and Notes are different object which point to the same reference of the array. In order to avoid such behavior you need a deep copy. Check this: http://stackoverflow.com/questions/129389/how-do-you-do-a-deep-copy-an-object-in-net-c-specifically[^]
Regards


这篇关于变量的更改也会更改数组元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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