我是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);
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句