struct 와 클래스의 차이
C#/Study 2019. 11. 2. 02:36class 는 참조 형식이고 struct는 값형식이다.
코드:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
|
using System;
using System.Collections.Generic;
using System.Text;
namespace Project
{
class App
{
public App()
{
classData a = new classData();
a.str = "홍길동";
classData b = a;
b.str = "이호준";
structedData structedData;
structedData structedData2 = structedData;
Console.WriteLine(a.str);
}
}
struct structedData
{
public string str;
}
class classData
{
public string str;
}
}
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
|
출력:

첫째 줄에는 값형식인 structedData.str 의 값이 다른 객체가 참조하는게 아니기 때문에 다른 객체에서 값을 바꿔도 structedData.str 의 값은 바뀌지 않는것이 확인 되었다.
둘째 줄에는 참조 형식인 a의 값을 다른 객체가 참조하기 때문에 다른객체에서 값을 바꾸면 a의 참조값도 바뀌게 되는것이 확인 되었다.
또한 class는 파생클래스를 가지고 파생이 될 수 있는 반면 struct는 인터페이스로부터만 파생이 가능하다.
예시:

'C# > Study' 카테고리의 다른 글
12.09 드래곤플라이트 2 (이펙트 추가) (0) | 2019.12.09 |
---|---|
12.02 객체 충돌 (0) | 2019.12.02 |
ref 와 out (0) | 2019.10.31 |
초기화 (0) | 2019.10.31 |
박싱과 언박싱 (0) | 2019.10.31 |