==> 속성.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는 넘겨온 값을 의미한다.
*/

Posted by holland14
: