Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
121 views
in Technique[技术] by (71.8m points)

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

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"
Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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("..");


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...