为什么我的对象集合中每次添加的都是同一个对象?

来源:百度知道 编辑:UC知道 时间:2024/06/15 22:40:11
我的代码如下:
e7560.Shopping.Model.PostedTypeModel post = new PostedTypeModel();
if( this.chboxPost.Checked == true )
{

post.PostTypeID = 1;
post.Charge = double.Parse( this.txtPostPay.Text);
post.AddedCharge = double.Parse( this.txtPostAdd.Text);
this.titem.Add( post );
}
if( this.chboxSend.Checked == true)
{

post .PostTypeID = 2;
post .Charge = double.Parse( this.txtSendPay.Text );
post .AddedCharge = double.Parse( this.txtSendAdd.Text);
this.titem.Add( post );
}
if( this.chboxEMS.Checked == true )
{
post .PostTypeID = 3;
post .Charge = double.Parse( this.txtEMSPay.Text );
post .AddedCharge = double.Parse( this.txtEMSAdd.Text);
this.titem.Add( post );
}
可是每次得到的三个对象都是一样的!全都是第三次添加的对象,为什么?集合不是应该每次添加一个吗?

汗,你的post根本就没重新实例化,总是同一个对象改变再存进去

而集合里存的是对象的引用,你3个都是同一对象当然引用也是同一个,所以3个就会一样, 改的话在没个if里面 将 post重新指向一个新对象,如

if( this.chboxEMS.Checked == true )
{
post = new 对象();//这里实例化
post .PostTypeID = 3;
post .Charge = double.Parse( this.txtEMSPay.Text );
post .AddedCharge = double.Parse( this.txtEMSAdd.Text);
this.titem.Add( post );
}