加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 如何克隆类实例?

发布时间:2020-12-15 04:17:23 所属栏目:百科 来源:网络整理
导读:所以我有这门课: 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 insta
所以我有这门课:
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.如果类支持克隆自身,则这是应该实现的默认接口.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读