List <t>中的对象引用相同的值</t>

时间:2014-06-11 08:00:36

标签: c# arrays list

我有一个自定义对象列表List<Slot> 每个Object Slot都有一个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);
    }
}

问题是,在每个Slot中,Genes是相同的,它们引用已添加到slotsList的最后一个lstGene []。

我又在哪里搞砸了?

3 个答案:

答案 0 :(得分:3)

您应该为每个itemtoadd创建新数组。

//For all slots
for (int i = 0; i < tempInt; i++)
{
    //for all genes
    Gene[] lstGene = InitializeArray<Gene>(lchromeSize);
    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);

}

答案 1 :(得分:2)

你需要移动这一行:

Gene[] lstGene = InitializeArray<Gene>(lchromeSize);

内部 for (int i = ..循环。您现在正在为每个插槽重复使用相同的阵列 - 这就是您所看到的。

答案 2 :(得分:1)

为什么不在循环中初始化 Gene [] lstGene ?否则,如果我没有弄错的话,你仍然会一遍又一遍地引用相同的数组