50. 속성(Property)
.NET프로그래밍/C# 3.5 SP1 2009. 8. 13. 17:29 |==> 속성.cs
using System;
public class 속성
{
public static void Main()
{
#region Car 클래스
Car sonata = new Car();
sonata.Name = "소나타";
sonata.Color = "Red"; // set
Console.WriteLine(sonata.Color); // get
sonata.Run(); // Red/소나타
#endregion
Person na = new Person();
na.Name = "홍길동";
na.Birth = "1988-02-05";
Console.WriteLine(na.Age); // 22
}
}
==============================================================================================
==> Car.cs
using System;
public class Car
{
private string _Name; // 필드
public string Name // 속성
{
get { return _Name; }
set { _Name = value; }
}
private string _Color;// 필드
public string Color // 속성
{
get { return _Color; }
set { _Color = value; }
}
public void Run()
{
Console.WriteLine("{0},{1}", _Name, Color);
}
}
==============================================================================================
==> Person.cs
using System;
public class Person
{
// 2.0까지
private string _Name;
public string Name
{
get { return _Name; }
set { _Name = value; }
}
// 쓰기 전용 생성 : 추가 로직
private string _Birth;
public string Birth
{
set
{
_Birth = value; // 넘겨온 값을 필드에 셋팅
Age = DateTime.Now.Year - Convert.ToDateTime(value).Year + 1;
}
}
// 3.5부터 : prop
public int Age { get; set; }
}
/*
- private한 필드를 public속성으로 외부에 공개
- value는 넘겨온 값을 의미한다.
*/
'.NET프로그래밍 > C# 3.5 SP1' 카테고리의 다른 글
52. 정수형인덱서와 문자열인덱서 (0) | 2009.08.13 |
---|---|
51. 인덱서(Indexer) (0) | 2009.08.13 |
49. 메서드 오버로드(Method Overload) - 다중정의(=여러번 정의) (0) | 2009.08.13 |
47. 메서드(Method) (0) | 2009.08.12 |
46. 소멸자(Destructor) (0) | 2009.08.11 |