List& lt; T& gt;中的对象参考相同的值 [英] Objects in List<T> reference same value
本文介绍了List& lt; T& gt;中的对象参考相同的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个自定义对象列表 List< Slot>
每个对象插槽都有一个Gene []
I have a list of custom objects List<Slot>
Each Object Slot has an array of Gene[]
对象插槽
public class Slot
{
private Gene[] _genes;
private int _fitness;
//...
public Slot(int count)
{
_genes = InitializeArray<Gene>(count);
Fitness = 0;
}
public Gene[] getChromosomes()
{
return Genes; //getter method
}
//Helper to init array
static T[] InitializeArray<T>(int length) where T : new()
{
T[] array = new T[length];
for (int i = 0; i < length; ++i)
{
array[i] = new T();
}
return array;
}
}
对象基因
public class Gene
{
private DateTime _date;
private int _tcode;
private byte _availabe;
private byte _duty;
private int _fitness;
//...
public Gene()
{
_fitness = 0;
}
}
主要
private List<Slot> slotsList = new List<Slot>();
//...
//...
private void init_population(int lchromeSize, int lpopulationSize)
{
slotsList.Clear();
Gene[] lstGene = InitializeArray<Gene>(lchromeSize);
//For all slots
for (int i = 0; i < tempInt; i++)
{
//for all genes
for (int ii = 0; ii < lchromeSize; ii++)
{
//assign values to local variables
// and :
lstGene[ii].Date = ldate;
lstGene[ii].Tcode = lteacherCode;
lstGene[ii].Availabe = lavailable;
lstGene[ii].Duty = tempDuty;
lstGene[ii].Fitness = 0;
}
//End ii For
//Add the genes to slotsList
Slot itemtoadd = new Slot(lchromeSize);
itemtoadd.setChromosomes(lstGene);
slotsList.Add(itemtoadd);
}
}
问题在于,每个插槽中的基因都是相同的,它们引用最后添加到slotList中的lstGene [].
The problem is that in every single Slot the Genes are identical and they reference the last lstGene[] that has been added to slotsList.
我又在哪里弄乱了?
推荐答案
您需要移动以下行:
Gene[] lstGene = InitializeArray<Gene>(lchromeSize);
位于 for(int i = ..
循环中.现在,您正在为每个插槽重新使用相同的数组-这就是您所看到的.
to be inside the for (int i = ..
loop. You are now re-using the same array for every slot - which is what you see.
这篇关于List& lt; T& gt;中的对象参考相同的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文