c# – 如何克隆类实例?

前端之家收集整理的这篇文章主要介绍了c# – 如何克隆类实例?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
所以我有这门课:
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.如果类支持克隆自身,则这是应该实现的默认接口.

原文链接:https://www.f2er.com/csharp/92233.html

猜你在找的C#相关文章