如何克隆类实例?

时间:2014-02-01 14:22:11

标签: 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;
    }
}

代码几乎解释了自己。我试图解决这个问题并想出了这个:

private Test(bool qwerty) {}

private Test GetClone()
{
    Test clone = new Test(true);
    clone.field1 = field1;
    clone.field2 = field2;
    return clone;
}

虽然我没有测试过,但我做得对吗?有没有更好的方法呢?

2 个答案:

答案 0 :(得分:8)

通常情况下,会为此编写一个复制构造函数:

public Test(Test other)
{
     field1 = other.field1;
     field2 = other.field2;
}

如果需要,您现在还可以添加克隆方法:

public Test Clone()
{
     return new Test(this);
}

更进一步,你可以让你的班级实施ICloneable。如果类支持克隆自身,则这是应该实现的默认接口。

答案 1 :(得分:3)

虽然有一个解决OP问题的答案,但我会添加另一个答案。要在不执行构造函数的情况下获取类的实例,请使用FormatterServices.GetUninitializedObject

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