更改数组的一个元素会更改其他元素 [英] Changing one element of an array changes others

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

问题描述

我有以下代码:

Chromosome[] pop = new Chromosome[popSize];      
int[] initialGenes = new int[i];  
for (int m = 0; m < i; m++)  
     initialGenes[m] = -1;  
     for (int j = 0; j < popSize; j++)  
     {                
        pop[j] = new Chromosome(graph, initialGenes);  
     }  

Chromosome 是我的类并且有一个属性

Chromosome is my class and has a property

public int[] Genes { get; set; }

如您所见,我初始化了一个 Chromosome 对象数组.问题是当我尝试更改 pop[i].Genes[k](例如 pop[1].Genes[2] = 123)的值时,所有 <pop 的 code>Genes[k] 被改变(即

As you can see I initialize an array of Chromosome objects. The problem is when I try to change the value of pop[i].Genes[k] (e.g. pop[1].Genes[2] = 123) all Genes[k] of pop are changed (i.e.

pop[0].Genes[2] == 123
pop[2].Genes[2] == 123 

等)

谁能解释一下是什么问题?
谢谢.

Could anyone explain what the problem is?
Thanks.

推荐答案

更改 Chromosome 的构造函数以复制传入的数组.
我假设,您的构造函数如下所示:

Change your constructor of Chromosome to make a copy of the array that is passed in.
I assume, your constructor looks like this:

public Chromosome(int[] initialGenes)
{
    Genes = initialGenes;
}

但它应该是这样的:

public Chromosome(int[] initialGenes)
{
    Genes = new int[initialGenes.Length];
    Array.Copy(initialGenes, Genes, Genes.Length);
}

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

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