[C# 객체지향] 멤버 유형 확장1_읽기 전용 필드(readonly)와 상수(const)

eunjin lee·2022년 7월 18일
0

C# 9.0 프로그래밍

목록 보기
15/50
  1. 읽기 전용 필드(readonly)
  • 변수를 정의할 때와 생성자를 제외하고는 그 값을 바꿀 수 없다.
  • setter 없이 구현하면 readonly를 사용하지 않아도 외부에서 값을 바꿀 수 없기는 하지만, readonly를 사용하면 클래스 내부에서도 값의 불변을 보장한다.
    ✍ 샘플 코드
    class Marriage
    {
        readonly int year = 2020; //정의 시 대입
        readonly string groom;
        readonly string bride;

        Boolean isDivorced;
        int children;

        public Marriage(string groom, string bride)
        {
            this.groom = groom;
            this.bride = bride; 
        }

        public void changeSpouse(string newName)
        {
            this.groom = newName; // 컴파일 에러
        }

        public void changeYear(int year)
        {
            this.year = year; // 컴파일 에러
        }

        public void getChild()
        {
            children++;//가능함.
        }

        public void getDivorce(Boolean divorce)
        {
            this.isDivorced = divorce;//가능함
        }
    }

  1. 상수(const)
  • 변하지 않는 값인 리터럴에 식별자를 붙인 것이다.
    ✍ 샘플 코드
    class Marriage
    {
        const string requirement = "Love";
        const Boolean isImportant = true;
    }

  1. readonly vs const
  • 상수는 static 예약어가 허용되지 않는다.(의미상 이미 static에 해당한다.)
  • 상수는 기본자료형에 대해서만 정의가 허용된다.
  • 상수는 정의 시 값을 대입해야 한다. 즉, 생성자에 접근할 수 없다.
  • 상수는 컴파일할 때 해당 소스코드에 값이 직접 치환된다.

0개의 댓글