c# - 如何克隆类实例?

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

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

最佳答案

通常,人们会为此编写一个复制构造函数:

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/

相关文章:

java - 作业概览 说明

c++ - 虚拟继承

java - 区分构造函数内的子类

c# - SAP HANA Entity Framework

c# - oData 中的集合名称列表

c# - 在 C# 中测试控制台输入和输出控制台应用程序

c# - 从 Controller 访问它时,我的 MvcApplication 的属性为 null

oop - 帮我命名我的类(class)

javascript - JS - 比较 2 个对象数组

java在第二类中找不到构造函数