C# 使用构造函数类创建现有类实例的副本
我是OOP新手,所以请容忍我。我在使用类构造函数复制现有类时遇到问题。下面是一个示例,在这个示例中,我创建了一个类的初始实例,使用类构造函数复制它,然后修改初始类中的属性值。这也修改了复制类中的相同值,这不是我想要实现的行为。(我希望它保持为修改前的初始类。)提前感谢您的帮助C# 使用构造函数类创建现有类实例的副本,c#,copy-constructor,C#,Copy Constructor,我是OOP新手,所以请容忍我。我在使用类构造函数复制现有类时遇到问题。下面是一个示例,在这个示例中,我创建了一个类的初始实例,使用类构造函数复制它,然后修改初始类中的属性值。这也修改了复制类中的相同值,这不是我想要实现的行为。(我希望它保持为修改前的初始类。)提前感谢您的帮助 class Program { static void Main(string[] args) { // Make initial instance, make a copy, and wr
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当前,复制构造函数只需将
另一个实例的引用
分配给正在创建的MyClass
的当前实例。这导致了这样一个事实:对原始数组的任何更改都将对新创建的类可见,因为它们指向同一数组。实际上,您要做的是在复制构造函数中复制数组
public MyClass(MyClass anotherInstance)
{
Array.Copy(anotherInstance.AllPoints,
this.AllPoints,
anotherInstance.AllPoints.Length);
}
数组声明是否将double从值类型更改为ref类型?@PITaylor。我不太清楚你在问什么。您指的是哪个数组声明?@PITaylor,
double
是值类型,而double[]
是引用类型。这是两种不同的类型;它们之间的唯一关系是double[]
是一种数组类型,其元素类型为double
@DanBryant既然有了引用,您知道我可以在c源代码的哪里查找[,]的代码吗?@PITaylor[,]
是二维数组声明的关键字。你可以