【发布时间】:2014-05-07 02:00:41
【问题描述】:
这段代码的结果是“1”和“2”。当我拆分 Foo "a" 时,它会生成一个实例 "b" 以及我对 "b" 所做的一切,它也会发生在 "a" 上。 是否有任何解决方案可以返回一个完全独立的 Foo 实例?所以我的代码的结果是“1”和“1”。
using System.IO;
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
Baar b0 = new Baar();
Baar b1 = new Baar();
Baar b2 = new Baar();
Baar b3 = new Baar();
Foo a = new Foo(200);
a.addBaar(b0);
Console.WriteLine(a.baars.Count);
Foo b = a.split(100);
b.addBaar(b1) ;
Console.WriteLine(a.baars.Count);
}
}
class Foo
{
public int amount;
public List<Baar> baars = new List<Baar>();
public Foo(int amount)
{
this.amount = amount;
}
private Foo(int amount, List<Baar> baars)
{
this.amount = amount;
this.baars = baars;
}
public void addBaar(Baar baar)
{
this.baars.Add(baar);
}
public Foo split(int amount)
{
int diff = this.amount - amount;
this.amount = amount;
return new Foo(diff, this.baars);
}
}
class Baar
{
public Baar()
{
}
}
【问题讨论】:
-
"这段代码的结果是 "1" 和 "2"。
...所以我的代码的结果是 "1" 和 "2"。" -- 是其中一个错字,还是您的代码已经完成了您想要的操作? -
Deep cloning objects 的可能重复项
-
是的,这是一个错字。哈哈。我已经更正了。
-
我已经编辑了你的标题。请参阅“Should questions include “tags” in their titles?”,其中的共识是“不,他们不应该”。