fox*_*eSs 6 c# oop constructor instance
所以我有这门课:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
代码几乎解释了自己.我试图解决这个问题并想出了这个:
private Test(bool qwerty) {}
private Test GetClone()
{
Test clone = new Test(true);
clone.field1 = field1;
clone.field2 = field2;
return clone;
}
Run Code Online (Sandbox Code Playgroud)
我没有测试过,但我做得对吗?有没有更好的方法呢?
通常,人们会为此编写一个复制构造函数:
public Test(Test other)
{
field1 = other.field1;
field2 = other.field2;
}
Run Code Online (Sandbox Code Playgroud)
如果需要,您还可以立即添加克隆方法:
public Test Clone()
{
return new Test(this);
}
Run Code Online (Sandbox Code Playgroud)
更进一步,你可以让你的班级实施ICloneable.如果类支持克隆自身,则这是应该实现的默认接口.