在每次迭代之后,全局列表采用新值并且不保留前一个值

时间:2015-12-16 06:30:08

标签: c# list

public class trials
{
    public string Tname;
    public List<String> Item=new List<string>();
    public List<String> Duration = new List<string>();
}

List<trials> mtrials = new List<trials>();

List<String> temp_Item = new List<string>();
List<String> temp_Duration = new List<string>();

private void button8_Click(object sender, EventArgs e)
{
    mtrials.Add(new trials { 
              Tname = textBox9.Text, 
              Item = temp_Item,      
              Duration = temp_Duration });
    temp_Duration.Clear();
    temp_Item.Clear();
} 

mtrialstemp_Itemtemp_duration是全局列表。我的问题是,每次迭代后,mtrials值也会发生变化。我不知道为什么会发生这种情况,因为一旦我将值赋予mlist,我就会清除它们以便我可以保留新值。 temp_itemtemp_duration充当了保存大量数据的列表。

4 个答案:

答案 0 :(得分:3)

当您在列表中运行Clear()时,您正在修改刚刚提供给mtrials的相同引用。

mtrials.Add(new trials { 
              Tname = textBox9.Text, 
              Item = temp_Item, //<--- This is pointing to the same list    
              Duration = temp_Duration });
temp_Item.Clear();              //<--- As this one. You need to create a new list instead.

将清除替换为:

temp_Duration = new List<string>();
temp_Item = new List<string>()

答案 1 :(得分:1)

Item = temp_Item; temp_item.Clear ();您正在使用相同的引用清除相同的列表,因此ItemDuration始终为空。 您无法跳过temp_item.Clear ();

private void button8_Click(object sender, EventArgs e)
{
    mtrials.Add(new trials { 
              Tname = textBox9.Text, 
              Item = temp_Item,      
              Duration = temp_Duration });
} 

答案 2 :(得分:0)

而不是清除&#34; temp_Duration&#34;和&#34; temp_Item&#34; 使用

string s1 = temp_Duration [temp_Duration.Count - 1]; string s2 = temp_Item [temp_Item.Count - 1];

答案 3 :(得分:0)

private void btnIncarcaLista_Click(object sender, EventArgs e)
        {            
            mtrials.Add(new trials
            {
                Tname = textBox9.Text,
                Item = new List<string>(temp_Item),
                Duration = new List<string>(temp_Duration)
            });
            temp_Duration.Clear();
            temp_Item.Clear();
        }

Item = temp_Item在Item字段中创建对temp_Item的引用,当您Clear()temp_Item时,Item字段也被清除。 如果您根据temp_Item的信息创建新列表,例如Item = new List<string>(temp_Item),,那么即使您清除了temp_Item,也会保留信息。

相关问题