数组重复一个值
本文关键字:一个 数组 | 更新日期: 2023-09-27 18:14:38
我已经填充了这个对象的数组,我认为我正在填充它,直到我要求重复我刚刚填充的内容,并看到它们都是相同的结果。我知道这很简单,但我现在却错过了它。
static void Main(string[] args)
{
int numOFItems = 6;
int population = 10;
int[] geneList = new int[numOFItems];
Genome[] gen = new Genome[population];
Random rand = new Random();
Genome gene;
for (int i = 0; i < population; i++)
{
gen[i] = new Genome();
for (int j = 0; j < numOFItems; j++)
{
geneList[j] = rand.Next(0, 4);
}
gene = new Genome(geneList);
gen[i] = gene;
Console.Out.Write("'n" + gen[i].ToString());
}
for (int i = 0; i < population; i++)
Console.Out.Write("'n" + gen[i].ToString() + ";");
Console.ReadLine();
}
class Genome
{
int[] geneList;
int numOFItems = 6;
public Genome()
{
geneList = new int[numOFItems];
}
public Genome(int[] geneList)
{
this.geneList = geneList;
}
public int[] GeneList
{
get { return geneList; }
set { geneList = value; }
}
public override string ToString()
{
return "" + GeneList[0] + GeneList[1] + GeneList[2]
+ GeneList[3] + GeneList[4] + GeneList[5];
}
}
您只初始化geneList
一次-因此每个Genome
包含对同一数组的引用。将geneList
的声明和初始化移到循环中。注意,还在列表的开始处创建了一个新的Genome
实例,然后覆盖它。所以我认为你的循环应该是这样的:
for (int i = 0; i < population; i++)
{
int[] geneList = new int[numOFItems];
for (int j = 0; j < numOFItems; j++)
{
geneList[j] = rand.Next(0, 4);
}
gen[i] = new Genome(geneList);
}
在每次迭代时,为参考基因分配一个新的Genome(geneList),然后为参考基因[i]分配基因所指向对象的地址。依此类推,最后您将始终获得所有对象为最后生成的Genome()的值,因为您一直覆盖由基因指向的内存位置。尝试将新的Genome(geneList)直接分配给gen[i].
移动geneList数组的声明,使其位于for循环中:
static void Main( string[] args )
{
int numOFItems = 6;
int population = 10;
Genome[] gen = new Genome[population];
Random rand = new Random ();
for( int i = 0; i < population; i++ )
{
int[] geneList = new int[numOFItems];
for( int j = 0; j < numOFItems; j++ )
{
geneList[j] = rand.Next (0, 4);
}
gen[i] = new Genome (geneList);
Console.Out.Write ("'n" + gen[i].ToString ());
}
for( int i = 0; i < population; i++ )
{
Console.Out.Write ("'n" + gen[i].ToString () + ";");
}
Console.ReadLine ();
}
(我也简化了你的代码)
否则,您只使用一个geneList-array,每次在循环中修改它,但是每个Genome实例都使用相同的geneList-array。(也就是说,它们都对该数组使用相同的引用)