C# Property

Chan·2021년 12월 3일
0

C#

목록 보기
9/10

프로퍼티

  • 할당 연산자  "=" 를 이용한 필드 액세스의 유혹 ⇒ 클래스 밖에서 사용할 때
  • 데이터의 오염 가능성이 높아짐
  • Get/Set 메소드를 사용한 필드 은닉
  • 은닉성과 편의성을 모두 잡는 방법 ⇒ 프로퍼티
  • 원래 필드 액세스 형식 - 사용하기 불편
class MyClass
{
    private int myField;
    public int GetMyField() { return myField; }
    public void SetMyField(int NewValue) { myField = NewValue; }
}
//----------------------//
MyClass obj = new MyClass();
obj.SetMyField(3);
System.Console.WriteLine(obj.GetMyField());
  • 프로퍼티 선언 형식
  • set 접근자를 구현하지 않으면 해당 프로퍼티를 쓰기불가 ⇒ 읽기전용
class MyClass
{
    private int myField;
    public int MyField
    {
        get // 기존 코드에서 GetMyField, SetMyField메소드를 프로퍼티로 변경
        {
            return myField;
        }

        set
        {
            myField = value;
        }
    }
}



자동 구현 프로퍼티

  • C# 7.0이후에는 자동 구현 프로퍼티를 선언함과 동시에 초기화를 수행 할수 있다.
public class NameCard
{
    private string name;
    private string phoneNumber;

    public string Name { get; set; } = "Unknown";

    public string PhoneNumber { get; set; } = "000-000";
}

프로퍼티를 이용한 초기화


using System;

namespace ConstructorWithProperty
{
    class BirthdayInfo
    {
        public string Name
        {
            get;
            set;
        }

        public DateTime Birthday
        {
            get;
            set;
        }

        public int Age
        {
            get
            {
                return new DateTime(DateTime.Now.Subtract(Birthday).Ticks).Year;
            }
        }
    }

    class MainApp
    {
        static void Main(string[] args)
        {
            BirthdayInfo birth = new BirthdayInfo()
            {
                Name = "서현", // 프로퍼티를 이용한 초기화
                Birthday = new DateTime(1991, 6, 28) // 프로퍼티를 이용한 초기화
            };

            Console.WriteLine("Name : {0}", birth.Name);
            Console.WriteLine("Birthday : {0}", birth.Birthday.ToShortDateString());
            Console.WriteLine("Age : {0}", birth.Age);
        }
    }
}

// 출력결과
Name : Unknown
Birthday : 0001-01-01
Age : 2021
Name : 서현
Birthday : 1991-06-28
Age : 30
profile
Backend Web Developer

0개의 댓글