C#中深度復制和淺度復制詳解
本文章主要是講解C# 語言編程中,深度復制和淺度復制,下面我將通過一個實例進行講解。在實例開發(fā)之前,我們得先知道深度復制是什么和淺度復制是什么,它們之間的區(qū)別又是什么,下面將為大家一一揭曉。
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;
}
}
}
//主函數(shù)
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);
}
}
}
通過簡單的實例開發(fā),大家對深度復制和淺度復制是不是有了大概的了解了,以后再有相關的內(nèi)容介紹會在和大家分享哦
相關文章
c#入門之循環(huán)語句使用詳解(for循環(huán)、do/while)
這篇文章主要介紹了c#入門之循環(huán)語句使用詳解,有for循環(huán)和do/while的示例,需要的朋友可以參考下2014-04-04
DevExpress之TreeList用法實例總結(jié)
這篇文章主要介紹了DevExpress之TreeList用法,對于C#初學者有一定的借鑒價值,需要的朋友可以參考下2014-08-08
C# WinForm應用程序降低系統(tǒng)內(nèi)存占用方法總結(jié)
這篇文章主要介紹了C# WinForm應用程序降低系統(tǒng)內(nèi)存占用方法總結(jié),本文總結(jié)了9個方法,同時給出了一個定期清理執(zhí)行垃圾回收代碼,需要的朋友可以參考下2014-10-10
C#開發(fā)WinForm項目實現(xiàn)HTML編輯器
這篇文章介紹了C#開發(fā)WinForm項目實現(xiàn)HTML編輯器的方法,文中通過示例代碼介紹的非常詳細。對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2022-06-06

