C# · 12月 25, 2021

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.如果类支持克隆自身,则这是应该实现的默认接口.