使用构造函数类制作现有类实例的副本

凯文·切伦奇克

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

尤瓦尔·伊茨恰科夫(Yuval Itzchakov)

当前,您的副本构造函数仅将的引用分配给正在创建anotherInstance的当前实例MyClass这导致这样一个事实,即新创建的类指向原始数组时,对原始数组的任何更改都将可见您实际要做的是在复制构造函数中复制数组

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

使用私有构造函数来防止类的实例化?

类型类实例化中的现有常量(例如,构造函数)

类构造函数 - 没有构造函数的实例

快速制作传递的类实例的副本

具有动态字段的Scala案例类副本构造函数

如何使用类构造函数为类实例定义接口

隐藏抽象基类的副本构造函数

如何调用父类副本构造函数?

以最小的影响向现有类添加构造函数

创建具有私有构造函数的类模板的实例

具有基类参数的派生类的副本构造函数的排序

使用私有构造函数扩展类

如何确保不能使用反射从类外部创建具有私有构造函数的类的实例?

Matlab类在构造函数中具有实例名称的知识

具有隐藏构造函数的抽象类的实例

Java:实例化没有默认构造函数的通用类

如何使用反射为构造函数中有参数的类创建对象实例?

如何使用带有Groovy闭包的构造函数参数实例化Java抽象类

如何使用 std::vector 动态实例化具有参数化构造函数的类?

使用构造函数初始化类实例与赋值之间有什么区别吗?

使用带有另一个类似类的参数的辅助构造函数创建数据类实例

如何使用超类的构造函数创建子类的实例

如何使用超类构造函数创建子类的实例?

使用不同的构造函数为不同的类创建实例

通过使用不同的构造函数创建类的实例

使用类名称创建实例并调用构造函数

使用模板化构造函数实例化非模板类

在子类实例化中使用替代超类构造函数

如何实例化使用构造函数扩展类的特征