简体   繁体   中英

How to make clone of class instance?

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.

While there's an answer, which solves OP problem, I'll add another one, which answers the question. To get instance of class without executing its constructor, use FormatterServices.GetUninitializedObject :

var uninitializedObject = (MyClass)FormatterServices.GetUninitializedObject(typeof(MyClass));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM