본문 바로가기
Programming Language/C#

[C#] 프로퍼티

by dbxxrud 2019. 9. 28.

 

프로퍼티 - '속성'이라고 의미를 가지고 있는 프로퍼티는 전용 필드의 값을 읽거나 쓸 수 있는 유연한 메커니즘이다. 데이터의 쉽게 접근할 수 있으며, 메서드의 안정성과 유연성 수준을 올려주는데 도움이 된다.

 

 

 

프로퍼티 더 알아보기

 

클래스를 작성하다 보면 필드를 public과 private 중에 무엇으로 선언할지 고민하는 경우가 있다. 은닉성을 지키자니 번거롭고, 모든 public으로 선언하자니 은닉성이 신경 쓰이는 상황에 놓인다. 하지만 프로퍼티를 이용한다면 은닉성과 편의성, 둘 다 잡을 수 있다.

하지만 필드와 달리 프로퍼티는 변수로 분류되지 않기 때문에 ref 또는 out 매개변수로 전달할 수 없다.

 

 

 

선언

 

출력 결과는 5

프로퍼티 선언 문법에서 get과 set을 일컬어 '접근자'라고 한다. get 접근자는 필드로부터 값을 읽어오고 set 접근자는 필드에 값을 할당한다. set 접근자 안에 있는 'value' 키워드에 주목할 필요가 있는데, 비록 프로그래머가 선언한 적이 없지만 C# 컴파일러는 set접근자의 암묵적 매개변수로 간주하기 때문에 아무런 문제를 삼지 않는다. 

이제 MyClass의 객체는 '=' 할당 연산자를 통해 number 필드에 데이터를 저장하고 또 반대로 데이터를 읽어 올 수도 있다.

 

 

메서드보다 프로퍼티

 

 

 

프로퍼티로 작성한 코드를 Get과 Set 메서드를 이용해서 바꾸어 본 것이다. 확실히 프로퍼티가 좀 더 깔끔하고 유연성 있다.

 

 

 

get 접근자

 

get 접근자는 형식의 값을 반환해야 한다. get 접근자의 실행은 필드의 값을 읽는 것과 마찬가지이다. 메서드를 통해 필드가 변경되고 싶지 않을 때 Set 메서드를 구현하지 않는 것처럼,  프로퍼티를 통해 필드가 변경되지 않기를 원할 때도 set 접근자를 구현하지 않으면 해당 프로퍼티는 쓰기 불가, 다른 말로 읽기 전용 프로퍼티가 되는 것이다. 또한 get 접근자는 return과 throw 문으로 끝나야 한다. 

 

읽기 전용 이므로, 할당 불가!

 

또한 get 접근자를 이용한 개체의 상태를 변화하는 것은 잘못된 방법이다. number 필드에 접근할 때마다 개체의 상태가 변경되는 부작용을 초래할 수도 있기 때문이다.

 

부작용 초래

 

 

또한 get 접근자를 이용해서 필드 값을 반환하거나 계산 후에 반환할 수 도있다.

 

 

 

set 접근자 

 

set 접근자는 반환 형식이 void 인 메서드와 비슷하다. 또한 value라는 암시적 매개변수를 사용한다. 

set 접근자를 이용하여 name에 값을 할당하는 것을 볼 수 있다.

 

 

쓰기 전용 프로퍼티도 만들 수 있지만 다른 프로그래머들에게 쓰기 전용 프로퍼티의 용도와 동작 결과를 확인할 수 있는 방법을 알려줄 수 있어야 한다. 그렇지 않다면 그 프로퍼티는 코드를 관리하기 어렵게 만드는 하나의 원인이 될 가능성이 있기 때문이다.

 

 

예제

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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static System.Console;
using System.IO;
 
namespace Practice2
{
    class BirthdayInfo
    {
        private string name;
        private DateTime birthday;
 
        public string Name
        {
            get
            {
                return name;
            }
            set
            {
                name = value;
            }
        }
        public DateTime Birthday
        {
            get
            {
                return birthday;
            }
            set
            {
                birthday = value;
            }
        }
        public int Age
        {
            get
            {
                return new DateTime(DateTime.Now.Subtract(birthday).Ticks).Year;
            }
        }
    }
    class MainApp
    {
        static void Main(string[] args)
        {
            BirthdayInfo birth = new BirthdayInfo();
            birth.Name = "태형";
            birth.Birthday = new DateTime(1995724);
 
            WriteLine($"Name : {birth.Name}");
            WriteLine($"Birthday : {birth.Birthday.ToShortDateString()}");
            WriteLine($"Age : {birth.Age}");
        }
    }
}
 
http://colorscripter.com/info#e" target="_blank" style="color:#e5e5e5text-decoration:none">Colored by Color Scripter
http://colorscripter.com/info#e" target="_blank" style="text-decoration:none;color:white">cs

 

 

 

 

 

자동 구현 프로퍼티 

 

프로퍼티는 데이터의 오염에 대해선 메서드처럼 안전하고, 데이터를 다룰 때는 필드처럼 간결하다. 하지만 추가적인 논리가 필요하지 않을 때 자동 구현 프로퍼티를 통해 프로퍼티 선언이 더욱 간결해질 수 있다. 

 

수정전

 

수정후

 

두 코드를 비교하면 수정 후의 코드가 더욱 간결해졌다. 필드를 선언할 필요도 없고, 그저 get 접근자와 set 접근자 뒤에 세미콜론만 붙여주면 된다. 

 

C# 7.0부터 자동 구현 프로퍼티를 선언과 동시에 초기화를 수행할 수 있다. 자동 구현 프로퍼티에 초기값이 필요할 때 생성자에 초기화 코드를 작성하는 수고를 덜 수 있다.

 

초기화

 

 

예제

 

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
38
39
40
41
42
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static System.Console;
using System.IO;
 
namespace Practice2
{
    class BirthdayInfo
    {
        public string Name { get; set; } = "Unknown";
        public DateTime Birthday { get; set; } = new DateTime(111);
        public int Age
        {
            get
            {
                return new DateTime(DateTime.Now.Subtract(Birthday).Ticks).Year;
            }
        }
    }
 
    class MainApp
    {
        static void Main(string[] args)
        {
            BirthdayInfo birth = new BirthdayInfo();
            WriteLine($"Name : {birth.Name}");
            WriteLine($"Birthday : {birth.Birthday.ToShortDateString()}");
            WriteLine($"Age : {birth.Age}");
 
            birth.Name = "태형";
            birth.Birthday = new DateTime(1995724);
 
            WriteLine($"Name : {birth.Name}");
            WriteLine($"Birthday : {birth.Birthday.ToShortDateString()}");
            WriteLine($"Age : {birth.Age}");
        }
    }
}
 
http://colorscripter.com/info#e" target="_blank" style="color:#e5e5e5text-decoration:none">Colored by Color Scripter
http://colorscripter.com/info#e" target="_blank" style="text-decoration:none;color:white">cs

 

결과

 

 

프로퍼티와 생성자

 

객체를 생성할 때 각 필드를 초기화하는 또 다른 방법으로 프로퍼티를 이용한 초기화다. 

 

클래스 이름 인스턴스 = new 클래스 이름() {

프로퍼티 1 = 값,

프로퍼티 2 = 값,

프로퍼티 3 = 값

};

 

 

예제

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
38
39
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static System.Console;
using System.IO;
 
namespace Practice2
{
    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(1995724)
            };
            WriteLine($"Name : {birth.Name}");
            WriteLine($"Birthday : {birth.Birthday.ToShortDateString()}");
            WriteLine($"Age : {birth.Age}");
        }
    }
}
 
http://colorscripter.com/info#e" target="_blank" style="color:#e5e5e5text-decoration:none">Colored by Color Scripter
http://colorscripter.com/info#e" target="_blank" style="text-decoration:none;color:white">cs

 

 

 

※ 혼자서 공부하며 정리하는 블로그 입니다.

잘못된 부분이 있으면 알려주세요 :)

 

참고서적 : 이것이 C# 이다.

참고사이트 : MSDN

'Programming Language > C#' 카테고리의 다른 글

[C#] 인터페이스의 프로퍼티  (0) 2019.10.02
[C#] 무명 형식  (0) 2019.10.02
[C#] 추상 클래스  (0) 2019.09.12
[C#] 분할 클래스  (0) 2019.08.11
[C#] ToCharArray()  (0) 2019.05.23