使用构造函数类生成现有类实例的副本

本文关键字:实例 副本 构造函数 | 更新日期: 2023-09-27 18:20:34

我是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

使用构造函数类生成现有类实例的副本

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

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