使用构造函数类来创建现有类实例的副本

时间:2015-11-04 13:21:04

标签: c# copy-constructor

我是OOP的新手,所以请耐心等待我。我在使用类构造函数制作现有类的副本时遇到问题。下面是一个示例,我创建一个类的初始实例,使用类构造函数创建它的副本,然后修改初始类中的属性值。这也修改了复制类中的相同值,这不是我想要实现的行为。 (我希望它在修改之前保留为初始课程。)提前感谢您的帮助!

class Program
{
    static void Main(string[] args)
    {
        // Make initial instance, make a copy, and write the copied values to console
        myClass myInitialInstance = new myClass();
        myClass myOtherInstance = new myClass(myInitialInstance);
        Console.WriteLine("Copied Instance: {0}, {1}, {2}", myOtherInstance.Input1[0], myOtherInstance.Input1[1], myOtherInstance.Input1[2]);

        // Make change to initial instance
        myInitialInstance.Input1 = new double[] { 10, 10, 10 };

        // Notice in the display that myOtherInstance inherits the {10,10,10} values from myInitialInstance
        Console.WriteLine("Initial Instance: {0}, {1}, {2}", myInitialInstance.Input1[0], myInitialInstance.Input1[1], myInitialInstance.Input1[2]);
        Console.WriteLine("Copied Instance: {0}, {1}, {2}", myOtherInstance.Input1[0], myOtherInstance.Input1[1], myOtherInstance.Input1[2]);
        Console.ReadKey();

    }
}

public class myClass
{
    public double[,] AllPoints { get; set; }
    public double[] Input1 { get { return GetRow(0); } set { SetRow(0, value); } }
    public double[] Input2 { get { return GetRow(1); } set { SetRow(1, value); } }

    private double[] GetRow(int i) { return new double[] { AllPoints[i, 0], AllPoints[i, 1], AllPoints[i, 2] }; }
    private void SetRow(int i, double[] value)
    {
        AllPoints[i, 0] = value[0];
        AllPoints[i, 1] = value[1];
        AllPoints[i, 2] = value[2];
    }

    public myClass() { AllPoints = new double[2, 3]; }

    public myClass(myClass anotherInstance) { AllPoints = anotherInstance.AllPoints; }
}

上面的代码产生以下输出:

复制的实例:0,0,0 初始实例:10,10,10 复制实例:10,10,10

我希望输出如下:

复制的实例:0,0,0 初始实例:10,10,10 复制实例:0,0,0

1 个答案:

答案 0 :(得分:9)

目前,您的复制构造函数只是将anotherInstance的引用分配给正在创建的MyClass的当前实例。这导致了对新创建的类可见的原始数组的任何更改,因为它们指向同一个数组。你真正想做的是复制你的拷贝构造函数中的数组

public MyClass(MyClass anotherInstance) 
{
    Array.Copy(anotherInstance.AllPoints,
               this.AllPoints, 
               anotherInstance.AllPoints.Length); 
}