Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
633 views
in Technique[技术] by (71.8m points)

c# - Changing one element of an array changes others

I have the following piece of code:

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 is my class and has a property

public int[] Genes { get; set; }

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 

etc.)

Could anyone explain what the problem is?
Thanks.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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;
}

But it should look like this:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...