Adding items to a LIST<> of objects results in

2020-01-25 11:14发布

List<BillOfLading> bolList = new List<BillOfLading>();

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

    newBol.BillOfLadingNumber = "CRXY99991231";
    bolList.Add(newBol);
}

I was expecting that bolList would container two different objects or values, but it appears that this simple code doesn't work. Any ideas?

Resulting Immediates:

bolList

Count = 2
    [0]: {kTracker.BillOfLading}
    [1]: {kTracker.BillOfLading}
bolList[0]
{kTracker.BillOfLading}
    _billOfLadingNumber: "CRXY99991231"
    BillOfLadingNumber: "CRXY99991231"
bolList[1]
{kTracker.BillOfLading}
    _billOfLadingNumber: "CRXY99991231"
    BillOfLadingNumber: "CRXY99991231"

标签: c# list loops
2条回答
你好瞎i
2楼-- · 2020-01-25 11:47

You've only created one object, and added it twice. The fact that you modified that object between the first and second add is irrelevant; the list contains a reference to the object you added, so later changes to it will apply.

You need to replace newBol.BillOfLadingNumber = ".."; with newBol = new BillOfLading("..");

查看更多
时光不老,我们不散
3楼-- · 2020-01-25 12:04

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.

查看更多
登录 后发表回答