C#中深度复制和浅度复制详解

本文章主要是讲解C# 语言编程中,深度复制和浅度复制,下面我将通过一个实例进行讲解。在实例开发之前,我们得先知道深度复制是什么和浅度复制是什么,它们之间的区别又是什么,下面将为大家一一揭晓。

1.深度复制是什么?

深度复制就是引用类型的复制。

2.浅度复制是什么?

浅度复制是值类型的复制。

以下是C#中深度复制和浅度复制的实例代码引用片段:

using System;

using System.Collections.Generic;

using System.Text;

namespace Test

{

public class Content

{

public int val;

}

//此处若是深度复制才继承ICloneable接口

//public class Cloner : ICloneable

public class Cloner

{

public Content MyContent = new Content();

public Cloner(int newVal)

{

MyContent.val = newVal;

}

//浅度复制

//使用System.Object.MemberwiseClone()进行浅度复制,使用getCopy方法.

public object getCopy()

{

return MemberwiseClone();

}

//深度复制:

public object clone()

{

Cloner clonedCloner = new Cloner(MyContent.val); //此处是实例化一个对象

return clonedCloner;

}

}

}

//主函数

using System;

using System.Collections.Generic;

using System.Text;

namespace Test

{

class Program

{

static void Main(string[] args)

{

Cloner mySource = new Cloner(5);

Cloner myTarget = (Cloner)mySource.getCopy();//深度为cloner

Console.WriteLine("MyTarget.Mycontent.Val={}",myTarget.MyContent.val);

mySource.MyContent.val = 2;

Console.WriteLine("MyTarget.Mycontent.Val={}", myTarget.MyContent.val);

}

}

}

通过简单的实例开发,大家对深度复制和浅度复制是不是有了大概的了解了,以后再有相关的内容介绍会在和大家分享哦

以上是 C#中深度复制和浅度复制详解 的全部内容, 来源链接: utcz.com/z/320719.html

回到顶部