重用Object无法正常工作

时间:2010-03-22 22:12:06

标签: c# asp.net-3.5 code-reuse

我正在重新使用创建的Object来改变Date和序数值,但最后我得到的6个对象与最后一个完全相同。

换句话说,我将对象添加为参考,我应该添加为

我应该继承我的Object以获得Copy()方法?

RecurringPayment rp, copy;

rp = new RecurringPayment
{
    ...
}
payments.Add(rp);  // add first object

copy = rp;  // Copy the original element
for (int i = 1; i <= 5; i++)
{
    copy.NextPaymentDate = copy.NextPaymentDate.AddDays(copy.RecurringTime * 7);
    copy.OrderOrdinal = copy.OrderOrdinal + 1;

    payments.Add(copy); // add 5 more with X weeks ahead
}

谢谢

2 个答案:

答案 0 :(得分:3)

您可以实现ICloneable,然后调用clone来获取对象的浅表副本!

如果你愿意,你可以这样实现(可能有更好的方法):

public object Clone()
{
    return MemberwiseClone();
}

答案 1 :(得分:2)

您最终不会得到6个对象。您最终会得到6个引用,所有引用都引用相同的单个对象

可能实施ICloneable,并致电Object.MemberwiseClone - 但我不确定是否愿意。相反,我很想尝试使RecurringPayment不可变,并添加一个方法WithNextPaymentDate(DateTime nextDate)或类似的东西,它创建一个具有给定值的新对象。您的代码将是这样的:

// Can't use object initializers on immutable types of course - all the
// values would have to be specified in the constructor call
RecurringPayment payment = new RecurringPayment(...);
payments.Add(payment);

for (int i = 1; i <= 5; i++)
{
    // This would automatically increment the OrderOrdinal in the newly
    // created object
    payment = payment.WithNextPaymentDate(payment.RecurringTime * 7);
    payments.Add(payment);
}