So I have this class:
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;
}
}
The code pretty much explains itself. I tried to solve that and came up with this:
private Test(bool qwerty) {}
private Test GetClone()
{
Test clone = new Test(true);
clone.field1 = field1;
clone.field2 = field2;
return clone;
}
I havent tested it out though, but am I doing it right? Is there better way to do that?
Normally, one would write a copy constructor for this:
public Test(Test other)
{
field1 = other.field1;
field2 = other.field2;
}
If you want, you can also add a Clone method now:
public Test Clone()
{
return new Test(this);
}
Going even further, you could have your class implement ICloneable
. This is the default interface a class should implement if it supports cloning of itself.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With