我的函数接受List类型的参数,如下所示:
private decimal CalculateIRR(List<AmortizationDepotResult> lstAmortizationDepotResult, decimal carryAmount)
{
if (lstAmortizationDepotResult.Count > 0)
{
var lstLoanDepots = lstAmortizationDepotResult.ToList();
lstLoanDepots.First().Payment = carryAmount;
在上面的代码中,我只想更改列表中第一个对象的参数值(Payment)
。如果我执行上面的代码,carryAmount
值会反映在lstAmortizationDepotResult
以及lstLoanDepots
中。
但我不想更改lstAmortizationDepotResult
中的值,它应仅反映在lstLoanDepots
中。
那我怎么解决我的问题???
谢谢..
答案 0 :(得分:1)
欢迎来到对象世界,您的变量不是值,而是引用。因此:
var a = new Foo();
var b = a;
a.Bar = "Hello!";
Console.WriteLine(b.Bar); // output = "Hello!"
如果要将对象的值复制到另一个相同的对象,使它们不共享相同的内存空间,则必须明确地执行此操作:
var b = new Foo
{
Bar = a.Bar,
OtherField = a.OtherField
};
答案 1 :(得分:0)
if (lstAmortizationDepotResult.Count > 0)
{
var lstLoanDepots = lstAmortizationDepotResult
.Select(x=> new AmortizationDepotResult{
Payment = carryAmount,
Property2 = x.Property2, Property3 = x.Property3, ....
})
.ToList();
// ...
创建一个新列表,但包含的所有对象都引用原始对象。如果需要列表中所有对象的深层副本,请提供适当的构造函数或手动初始化所有属性。
for
答案 2 :(得分:0)
我在您的IClonable
课程中实施AmortizationDepotResult
界面:
public class AmortizationDepotResult ...
IClonable {
...
Object IClonable.Clone() {
return Clone();
}
public AmortizationDepotResult Clone() {
AmortizationDepotResult result = new AmortizationDepotResult();
...
result.Payment = Payment;
...
return result;
}
}
因此,为了拥有深层复制,您可以
private decimal CalculateIRR(List<AmortizationDepotResult> lstAmortizationDepotResult, decimal carryAmount) {
if (lstAmortizationDepotResult.Count > 0) {
var lstLoanDepots = lstAmortizationDepotResult
.Select(item => item.Clone())
.ToList();
lstLoanDepots[0].Payment = carryAmount;
...
}