순서

I. Property
II. Property Example

 


I. Property

 

C#에서는 기본적인 get set Interface를 제공해준다.

C++같은 경우는 private member관련 public method를 만들어 사용자에게 제공한다.

C#에서도 구조는 동일하게 private member와 public method로 구성되고
public method를 수동으로 구현하거나 자동으로 구현되도록 할 수 있다.

즉, private field에 값을 읽거나 할당(get set) 할 때 언어차원에서 지원해주는 것.
이를 C#에서 Property라고 한다.

 


II. Property Example


1. public Property 수동 구현

 

using System;

namespace PropertyApp1 {
  class Triangle {
    private int _height;
    private int _width;
    
    public int height {
      get {return _height;}
      set { _height = value}; // value 아래 설명
    }
  }
  사용시 그냥 똑같이 변수쓰듯 쓰면 된다.
  Triangle.height = 3;
  int a = Triangle.height;
}

private형으로 은닉해주고 method를 만들어준다.

이때 get, set 내부에 함수를 직접 구현해준다.

value관련
만약에 height = myheight로 값 할당을 했을 때 rvalue가 System상에서 value로 들어온다.

 

2. public Property 자동 구현

 

using System;

namespace PropertyApp1 {
  class Triangle {  
    public int height {
      get;
      set;
    }
  }
  사용시 그냥 똑같이 변수쓰듯 쓰면 된다.
  Triangle.height = 3;
  int a = Triangle.height;
  
}

아래와같이 method처럼 구현해놓고 get; set;으로 만들어준다.

해당 class에는 private 변수가 없는데 위와 같이 구현을 하면
System 내부에서 자동으로 private 데이터를 관리하고 있다.

+ Recent posts