🌸 읽기 전용 필드: readonly
using System;
namespace ReadonlyFields
{
class Configuration
{
private readonly int min;
private readonly int max;
public Configuration(int v1, int v2)
{
min = v1;
max = v2;
}
public void PrintValue()
{
Console.WriteLine($"min: {this.min}, max: {this.max}");
}
}
class MainApp
{
static void Main(string[] args)
{
Configuration c = new Configuration(1, 2);
c.PrintValue();
}
}
}
[실행 결과]
min: 1, max: 2
🌸 구조체: struct
| 특징 | 클래스 | 구조체 |
|---|
| 키워드 | class | struct |
| 형식 | 참조 형식 | 값 형식 |
| 복사 | 얕은 복사 | 깊은 복사 |
| 인스턴스 생성 | new 연산자, 생성자 필요 | 선언만으로 생성 |
| 생성자 | 매개변수 없는 선언 가능 | 매개변수 없이 선언 불가능 |
| 상속 | 가능 | 불가능 (값 형식) |
| 변경 불가능 선언 | 불가능 | 가능 |
using System;
namespace Structure
{
struct Point3D
{
public int X; public int Y; public int Z;
public Point3D(int X, int Y, int Z)
{
this.X = X;
this.Y = Y;
this.Z = Z;
}
public override string ToString()
{
return string.Format($"{X}, {Y}, {Z}");
}
}
class MainApp
{
static void Main(string[] args)
{
Point3D p3d1;
p3d1.X = 10;
p3d1.Y = 20;
p3d1.Z = 30;
Console.WriteLine(p3d1.ToString());
Point3D p3d2 = new Point3D(100, 200, 300);
Console.WriteLine(p3d2.ToString());
Point3D p3d3 = p3d2;
p3d3.Z = 400;
Console.WriteLine(p3d2.ToString());
Console.WriteLine(p3d3.ToString());
}
}
}
[실행 결과]
10, 20, 30
100, 200, 300
100, 200, 300
100, 200, 400
✔️️ 변경 불가능 선언: readonly
using System;
namespace ReadonlyStruct
{
readonly struct RGBColor
{
public readonly byte R;
public readonly byte G;
public readonly byte B;
public RGBColor(byte r, byte g, byte b)
{
R = r;
G = g;
B = b;
}
}
class MainApp
{
static void Main(string[] args)
{
RGBColor Red = new RGBColor(255, 0, 0);
Console.WriteLine($"{Red.R}, {Red.G}, {Red.B}");
RGBColor myColor = new RGBColor(Red.R, 100, Red.B);
Console.WriteLine($"{myColor.R}, {myColor.G}, {myColor.B}");
}
}
}
[실행 결과]
255, 0, 0
255, 100, 0