这段代码哪里错了 怎么让数组也深度复制

.Net技术 码拜 8年前 (2016-02-29) 783次浏览
问一下这段代码哪里错了 怎么让数组也深度复制?哪位高手帮本人修改一下  谢谢了 高分献上!
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections;
namespace 带参的构造函数的深度复制
{
public class Test
{
public int Val;
public object Clone()
{
return MemberwiseClone();
}
}
public class Content
{
public Test Va = new Test();
public int[] shuzu = new int[5] ;
public int ziduan;
public Content(int[] shuzu1, int ziduan1,int newVal)
{
shuzu = shuzu1;
ziduan = ziduan1;
}
public Content()
{ }
public object Clone()
{
Content a = new Content(shuzu,ziduan,Va.Val);
a.Va = (Test)Va.Clone();

return a;
}
}
public class Cloner : ICloneable
{
public Content MyContent = new Content();
public Cloner(int newVal,Content a)
{
MyContent.Va.Val = newVal;
}
public object Clone()
{
Cloner clonedCloner = new Cloner(MyContent.Va.Val,MyContent);
clonedCloner.MyContent = (Content)MyContent.Clone();
return clonedCloner;
}
}
class Program
{
static void Main(string[] args)
{
int[] b=new int[5]{5,4,3,2,1};
Content a=new Content(b,3,6);
Cloner mySouce = new Cloner(5,a);
Cloner myTarget = (Cloner)mySouce.Clone();
Console.WriteLine(myTarget.MyContent.shuzu[0]);
mySouce.MyContent.shuzu[0]=108;
Console.WriteLine(myTarget.MyContent.shuzu[0]);
Console.WriteLine(mySouce.MyContent.shuzu[0]);
}
}
}

解决方案

40

        public Content(int[] shuzu1, int ziduan1, int newVal)
{
            shuzu = (int[])shuzu1.Clone();
            ziduan = ziduan1;
}

CodeBye 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权 , 转载请注明这段代码哪里错了 怎么让数组也深度复制
喜欢 (0)
[1034331897@qq.com]
分享 (0)