- Value Type => Stack memory์ ์ ์ฅ
- Reference Type => Heap memory์ ์ ์ฅ
[Ex.1 - Shallow Copy]
Demo1 demo1 = new Demo1();
demo1.aa = 100;
demo1.bb = 1000;
//Shallow Copy
Demo1 demo2 = demo1;
demo2.bb = 1111;
Console.WriteLine("{0} {1}", demo1.aa, demo1.bb);
Console.WriteLine("{0} {1}", demo2.aa, demo2.bb);
Output
100 1111
100 1111
- demo1 ์ aa ์ bb์ ์ฃผ์๊ฐ์ ๊ฐ์ง๊ณ ์๊ณ , aa์ bb์ ๊ฐ์ heap ๋ฉ๋ชจ๋ฆฌ์ ์ ์ฅ๋์ด ์๋ค.
- ๋ฐ๋ผ์ ์์ ๊ฐ์ ๋ณต์ฌ๋ demo1์ ์ ์ฅ๋ heap๋ฉ๋ชจ๋ฆฌ์ ์ฃผ์๋ฅผ demo2์ ํ ๋นํ ๊ฒ์ด๊ณ , demo2 ๋ demo1๊ณผ ๋ง์ฐฌ๊ฐ์ง๋ก ๊ฐ์ ์ฃผ์๋ฅผ ๊ฐ๋ฆฌํค๊ณ ์๋ค. ๋ฐ๋ผ์ demo2 ๊ฐ์ฒด๋ฅผ ํตํด bb์ ๊ฐ์ ๋ฐ๊ฟ๋ demo1๊ณผ demo2๊ฐ ๋์์ ๊ฐ๋ฆฌํค๊ณ ์๋ ์ฃผ์์ ํด๋นํ๋ ๋ณ์๊ฐ์ด ๋ฐ๋๊ฒ => Shallow Copy
[Ex.2 Deep Copy]
class Demo1
{
public int aa;
public int bb;
public Demo1 DeepCopy()
{
Demo1 newDemo1 = new Demo1();
newDemo1.aa = this.aa;
newDemo1.bb = this.bb;
return newDemo1;
}
}
static void Main(string[] args)
{
Demo1 demo1 = new Demo1();
demo1.aa = 100;
demo1.bb = 1000;
//Shallow Copy
Demo1 demo2 = demo1;
demo2.bb = 1111;
//Deep Copy
Demo1 demo3 = demo1.DeepCopy();
demo3.bb = 2222;
Console.WriteLine("{0} {1}", demo1.aa, demo1.bb);
Console.WriteLine("{0} {1}", demo2.aa, demo2.bb);
Console.WriteLine("{0} {1}", demo3.aa, demo3.bb);
}
Output
100 1111
100 1111
100 2222
- demo1์์ DeepCopy ๋ฉ์๋๋ฅผ ํตํด ์๋ก์ด ๊ฐ์ฒด๋ฅผ ์์ฑํ๊ณ demo3์๊ฒ ํด๋น ๊ฐ์ฒด๋ฅผ ๋๊ฒจ ์๋ก์ด ๊ฐ์ฒด๊ฐ ๊ฐ์ง๋ ํ๋๋ค์ ์ฃผ์๋ฅผ ๊ฐ๋ฆฌํค๊ฒ ํ์ฌ ์๋ก ๋ค๋ฅธ ๊ฐ์ฒด๊ฐ ๊ฐ์ ํ๋์ ์ฃผ์๋ฅผ ํฌ์ธํ ํ๊ฒ ํ์ง ์๋๋ค. => Deep Copy
๊ฒฐ๋ก
- ํด๋์ค๋ ๊ธฐ๋ณธ์ ์ผ๋ก ์ฐธ์กฐํ์์ ์ทจํ๊ณ ์๊ธฐ ๋๋ฌธ์ ์ผ๋ฐ ๋ค๋ฅธ ๋ณ์์ฒ๋ผ ๋ฐ์ดํฐ๋ฅผ ํ ๋นํ ๋๋ ์ฐธ์กฐํ์์ ๋ฐฉ์์ ์ทจํ๋ Heap memory ์ ์ฅ๋ฐฉ์์ ์ฌ์ฉํ๋ค => Heap Memory ์ ์ฅ๋ฐฉ์ = Deep Copy
class Myclass{
public int field1;
public int field2;
}
static void Main(string[] args){
Myclass source = new Myclass();
source.field1 = 10;
source.field2 = 20;
Myclass target = source;
target.field2 = 30;
Console.WriteLine($"{source.field1} {source.field2}");
Console.WriteLine($"{target.field1} {target.field2}");
}
shallow copy Output
10 30
10 30
using System;
using System.Threading;
class Myclass
{
public int field1;
public int field2;
public Myclass DeepCopy()
// ๊ฐ์ฒด๋ฅผ ํ์ ํ ๋นํด์ ๊ทธ๊ณณ์ ์์ ์ ๋ฉค๋ฒ๋ฅผ ์ผ์ผ์ด ๋ณต์ฌํด ๋ฃ๋๋ค.
{
Myclass newCopy = new Myclass();
newCopy.field1 = field1;
newCopy.field2 = field2;
return newCopy;
}
}
class Program {
static void Main(string[] args)
{
Myclass source = new Myclass();
source.field1 = 10;
source.field2 = 20;
Myclass target = source.DeepCopy();
target.field2 = 30;
Console.WriteLine($"{source.field1} {source.field2}");
Console.WriteLine($"{target.field1} {target.field2}");
}
}
deep copy Output
10 20
10 30
'๐ป Programming Language > C#' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
06. ์ ๊ทผ์ ํ์(Access Modifier) (0) | 2022.04.06 |
---|---|
05. this, this() ์์ฑ์ (0) | 2022.04.06 |
03. static ํ๋์ static ๋ฉ์๋ (0) | 2022.04.06 |
02. ์์ฑ์์ ์ข ๋ฃ์ (0) | 2022.04.06 |
01. ํด๋์ค์ ๊ฐ์ฒด (0) | 2022.04.05 |