Adding items to a LIST<> of objects results in duplicate Objects when using a NEW in a Loop

前端 未结 2 567
死守一世寂寞
死守一世寂寞 2020-11-28 15:50
List bolList = new List();

protected void Button1_Click(object sender, EventArgs e)
{
    BillOfLading newBol = new BillOfLa         


        
2条回答
  •  隐瞒了意图╮
    2020-11-28 16:31

    Flynn1179's answer is correct, but to answer your comment - you don't need a different variable for each object. You can do:

    protected void Button1_Click(object sender, EventArgs e)
    {
        BillOfLading newBol = new BillOfLading("AXSY1414114");
        bolList.Add(newBol);
    
        newBol = new BillOfLading("CRXY99991231");
        bolList.Add(newBol);
    }
    

    The important thing to understand is that you're not adding the variable to the list, nor are you adding the object to the list... you're adding the current value of the variable to the list. That current value is a reference to an instance of BillOfLading. In the above code, the list ends up with references to two different objects.

提交回复
热议问题