읽기 전용 필드, 구조체

Fruit·2023년 3월 29일

✨ Hello C#!

목록 보기
31/34
post-thumbnail

🌸 읽기 전용 필드: 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}");
        }

        /*
        public void ChangeValue()
        {
            this.min = 0;		// 생성자가 아닌 곳에서 값 수정 시도 → 에러 발생
            this.max = 0;
        }
        */
    }

    class MainApp
    {
        static void Main(string[] args)
        {
            Configuration c = new Configuration(1, 2);
            c.PrintValue();
        }
    }
}

[실행 결과]
min: 1, max: 2



🌸 구조체: struct

특징클래스구조체
키워드classstruct
형식참조 형식값 형식
복사얕은 복사깊은 복사
인스턴스 생성new 연산자, 생성자 필요선언만으로 생성
생성자매개변수 없는 선언 가능매개변수 없이 선언 불가능
상속가능불가능 (값 형식)
변경 불가능 선언불가능가능

using System;

namespace Structure
{
    struct Point3D
    {
        public int X; public int Y; public int Z;		//  편의를 위해 public으로 선언하는 경우가 많음

        public Point3D(int X, int Y, int Z)
        {
            this.X = X;
            this.Y = Y;
            this.Z = Z;
        }

        public override string ToString()       // System.Object - 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}");

            // Red.G = 100;         // readonly 로 에러 발생

            RGBColor myColor = new RGBColor(Red.R, 100, Red.B);         // 새로운 객체 생성
            Console.WriteLine($"{myColor.R}, {myColor.G}, {myColor.B}");
        }
    }
}

[실행 결과]
255, 0, 0
255, 100, 0
profile
🌼인생 참 🌻꽃🌻 같다🌼

0개의 댓글