所以我有这个类:
class Test
{
private int field1;
private int field2;
public Test()
{
field1 = // some code that needs
field2 = // a lot of cpu time
}
private Test GetClone()
{
Test clone = // what do i have to write there to get Test instance
// without executing Test class' constructor that takes
// a lot of cpu time?
clone.field1 = field1;
clone.field2 = field2;
return clone;
}
}
代码本身就很清楚了。我试图解决这个问题并想出了这个:
private Test(bool qwerty) {}
private Test GetClone()
{
Test clone = new Test(true);
clone.field1 = field1;
clone.field2 = field2;
return clone;
}
虽然我还没有测试过,但我做对了吗?有更好的方法吗?
最佳答案
通常,人们会为此编写一个复制构造函数:
public Test(Test other)
{
field1 = other.field1;
field2 = other.field2;
}
如果你愿意,你现在也可以添加一个克隆方法:
public Test Clone()
{
return new Test(this);
}
更进一步,您可以让您的类实现ICloneable
。如果一个类支持自身克隆,那么这是一个类应该实现的默认接口(interface)。
关于c# - 如何克隆类实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21499176/