2020. 1. 18. 18:01ㆍC# 언어/이것이 C# 이다. 책정리
챕터9 '프로퍼티' 입니다
객체 지향 언어의 "은닉성"을 표현하는 방법중 C#언어의 우아한 장치인
프로퍼티를 배웁니다!
'이것이 C#이다' 교재를 바탕으로 정리했습니다.
이전 정리글
2020/01/06 - [이것이 C# 이다./이것이 C# 이다. 책정리] - Ch01 프로그래밍을 시작합시다.
2020/01/06 - [이것이 C# 이다./이것이 C# 이다. 책정리] - Ch02 처음 만드는 C# 프로그램
2020/01/06 - [이것이 C# 이다./이것이 C# 이다. 책정리] - Ch03 데이터 보관하기
2020/01/07 - [이것이 C# 이다./이것이 C# 이다. 책정리] - 부록A. 문자열 다루기
2020/01/07 - [이것이 C# 이다./이것이 C# 이다. 책정리] - Ch04. 데이터를 가공하는 연산자
2020/01/08 - [이것이 C# 이다./이것이 C# 이다. 책정리] - Ch05 코드의 흐름 제어하기
2020/01/09 - [이것이 C# 이다./이것이 C# 이다. 책정리] - ch06 메소드로 코드 간추리기
2020/01/11 - [이것이 C# 이다./이것이 C# 이다. 책정리] - ch07 클래스
2020/01/17 - [이것이 C# 이다./이것이 C# 이다. 책정리] - ch08 인터페이스와 추상 클래스
ㅇ 메소드보다 프로퍼티 |
class 클래스이름
{
데이터형식 필드이름;
접근한정자 데이터형식 프로퍼티이름
{
get
{
return 필드이름;
}
set
{
필드이름 = value;
}
}
}
프로퍼티 선언 문법에서 get{}과 set{}을 일컬어 접근자 라고 합니다.
get 접근자는 필드로부터 값을 읽어오고
set 접근자는 필드에 값을 할당합니다.
set 접근자 안에 있는 value 키워드는 누구도 선언한 적이 없지만,
C# 컴파일러는 set 접근자의 암묵적 매개 변수로 간주하고 문제를 삼지 않습니다.
이용한 코드
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
|
using System;
using static System.Console;
namespace p310
{
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(
}
}
}
class MainApp
{
static void Main(string[] args)
{
BirthdayInfo birthday = new BirthdayInfo();
birthday.Name = "서현";
birthday.Birthday = new DateTime(1996, 6, 28);
WriteLine($"Name : {birthday.Name}");
WriteLine($"Birthday : {birthday.Birthday.ToShortDateString()}");
WriteLine($"Age : {birthday.Age}");
}
}
}
|
ㅇ 자동 구현 프로퍼티 |
프로퍼티는 데이터의 오염에 대해선 메소드처럼 안전하고, 데이터를 다룰 때는 필드처럼 간결합니다.
마이크로소프트의 C# 팀은 반복되는 프로퍼티를 한결 더 단순하게 만드는
자동 구현 프로퍼티를 c# 3.0 때 도입했습니다.
자동 구현 프로퍼티 구현 전
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
using System;
using static System.Console;
namespace ex
{
public class NameCard
{
private string name;
private string phoneNumber;
public string Name
{
get { return name; }
set { name = value; }
}
public string PhoneNumber
{
get { return phoneNumber; }
set { phoneNumber = value; }
}
}
|
자동 구현 프로퍼티 구현 후
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
using System;
using static System.Console;
namespace ex
{
public class NameCard
{
public string Naem
{
get; set;
}
public string PhoneNumber
{
get; set;
}
}
|
위 코드와 비교하면 엄청 간결해졌습니다.
필드를 선언할 필요도 없고, 그저 get, set 접근자 뒤에 세미콜론만 붙여주면 됩니다.
public class NameCard
{
public string Name { get; set; } = "Unknow";
public string PhoneNumber { get; set; } = "000-0000";
}
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
|
using System;
using static System.Console;
namespace p314
{
class BirthdayInfo
{
public string Name { get; set; } = "UnKnown";
public DateTime Birthday { get; set; } = new DateTime(1, 1, 1);
public int Age
{
get
{
return new DateTime(DateTime.Now.Subtract(Birthday).Ticks).Year;
}
}
}
class Program
{
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(1997, 3, 25);
WriteLine($"Name : {birth.Name}");
WriteLine($"Birthday : {birth.Birthday.ToShortDateString()}");
WriteLine($"Age : {birth.Age}");
}
}
}
|
ㅇ 프로퍼티와 생성자 |
객체를 생성할 때 매개 변수를 입력해서 객체의 각 필드를 초기화하는 방법을 배웠습니다.
이번에는 객체를 생성할 때 각 필드를 초기화하는 또 다른 방법을 소개하려 합니다.
클래스이름 인스턴스 = new 클래스이름()
{
프로퍼티1 = 값;
프로퍼티2 = 값;
프로퍼티3 = 값;
}
위와 같이 객체를 생성할 때 <프로퍼티 = 값> 목록에 객체의 모든 프로퍼티가 올 필요는 없습니다.
초기화하고 싶은 프로퍼티만 넣어서 초기화하면 됩니다.
앞에서 사용했던 BirthdayInfo 클래스를 예로 들면
BrithdayInfo birth = new BirthdayInfo()
{
Name = "서현";
Birthday = new DateTime(1991, 6, 28)
};
이처럼 사용할 수 있습니다.
이용한 코드
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
|
using System;
using static System.Console;
namespace p317
{
class BrithdayInfo
{
public string Name
{
get;
set;
}
public DateTime Birthday
{
get;
set;
}
public int Age
{
get
{
return new DateTime(
}
}
}
class MainApp
{
static void Main(string[] args)
{
BrithdayInfo brith = new BrithdayInfo()
{
Name = "서현",
Birthday = new DateTime(1996, 6, 13)
};
WriteLine($"Name : {brith.Name}");
WriteLine($"Birthday : {brith.Birthday.ToString()}");
WriteLine($"Age : {brith.Age}");
}
}
}
|
ㅇ 인터페이스의 프로퍼티 |
인터페이스는 메소드뿐만 아니라 프로퍼티와 인덱서도 가질 수 있습니다.
당연한 이야기겠지만 인터페이스에 들어가는 프로퍼티는 구현을 갖지 않습니다.
여기에 한 가지 문제가 있는데,
인터페이스의 프로퍼티 선언이 클래스의 자동 구현 프로퍼티 선언과 그 모습이 동일하다는 사실입니다.
이용한 코드
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
|
using System;
using static System.Console;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace p321
{
interface INamedalue
{
string Name
{
get;
set;
}
string Value
{
get;
set;
}
}
class NamedValue : INamedalue
{
public string Name { get; set; }
public string Value { get; set; }
}
class MainApp
{
static void Main(string[] args)
{
NamedValue name = new NamedValue()
{ Name = "이름", Value = "박상현" };
NamedValue height = new NamedValue()
{ Name = "키", Value = "123Cm" };
NamedValue weigth = new NamedValue()
{ Name = "몸무게", Value = "90kg" };
WriteLine($"{name.Name} : {name.Value}");
WriteLine($"{height.Name} : {height.Value}");
WriteLine($"{weigth.Name} : {weigth.Value}");
}
}
}
|
ㅇ 추상 클래스와 프로퍼티 |
추상 클래스는 클래스처럼 구현된 프로퍼티를 가질 수도 있고 구현되지 않은 프로퍼티를 가질 수도 있습니다.
파생 클래스가 해당 프로퍼티를 구현하도록 강제하는 것일 뿐이지요.
이용한 코드
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
|
using System;
using static System.Console;
namespace p324
{
abstract class Product
{
private static int serial = 0;
public string SerialID
{
get { return String.Format("{0:d5}", serial++); }
}
abstract public DateTime ProductDate
{
get;
set;
}
}
class MyProduct : Product
{
public override DateTime ProductDate
{ get; set; }
}
class MainApp
{
static void Main(string[] args)
{
Product product_1 = new MyProduct()
{ ProductDate = new DateTime(2018, 1, 10) };
WriteLine("Product : {0} Product Date : {1}",
product_1.SerialID,
product_1.ProductDate);
Product product_2 = new MyProduct()
{ ProductDate = new DateTime(2018, 2, 3) };
WriteLine("Product : {0} Product Date : {1}",
product_2.SerialID,
product_2.ProductDate);
}
}
}
|