在对象列表与LT; T>参考值相同 [英] Objects in List<T> reference same value

查看:126
本文介绍了在对象列表与LT; T>参考值相同的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有自定义对象的列表列表与LT;插槽>
每个对象插槽都有基因的数组[]

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

的问题是,在每一个槽的基因是相同的,并且它们引用的最后lstGene []已添加到slotsList

The problem is that in every single Slot the Genes are identical and they reference the last lstGene[] that has been added to slotsList.

在哪里做我搞砸一遍吗?

Where did I mess up it again ?

推荐答案

您需要移动这一行:

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.

这篇关于在对象列表与LT; T&GT;参考值相同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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