컴퓨터/정보처리기사 SW 공학

| 니앙팽이 - 객체지향(OOP) | 2-5 | 구조체

객체지향

📕 2. 객체지향 개발


📄 5. 구조체

1). 클래스 VS 구조체

  • 타입차이에 따른 메모리 할당
    ClassStruct
    타입ReferenceValue
    메모리할당HeapStack

stack

  • 지역 변수를 저장하며, 실행 중인 함수를 찾아 계산을 수행함
  • 변수들은 Stack으로 저장(후입선출)

heap

  • 참조 타입들이 이 곳에 할당된다.
  • 메모리 누수의 대상이 된다.

2). 클래스 써버리지 뭘.. 왜?

  • 아까말했듯 클래스는 힙영역에 할당된다. 반대로 구조체는 Stack에 들어가므로
    가비지컬렉터가 덜 일해도 된다.
    메소드를 쓰지 않고 오직 데이터만 그룹 시키고 싶을때, 딱좋다~!
  • 그리고 생성자 오버로딩에 사용되기도 한다.

3). 사용법

구조체가 가능한것

  • ⓐ 프로퍼티 : get, set
    • 예시
      class _className_ 
      {
          _type_ _fildName_;
          _접근한정자_ _type_ _프로퍼티명_{get; set;}
          _접근한정자_ _type_ _프로퍼티명_
          {
              get{return;}
              set{return;}
          }
      }
      
  • ⓑ 생성자
  • ⓒ 이벤트
  • ⓓ System.Object 매서드 readonly override

4). 참조

① C# 구조체를 써야하는 이유
② C# 구조체 (프로퍼티 & 생성자 & 이벤트)

  • property & constructor & event

    public struct Coords {
        private int _x, _y;
        public Coordinate(int x, int y) { this.x = x; this.y = y; }
            // 2. 생성자 
                //_접근한정자_ _type_ _프로퍼티명_{get{...}; set{...};}
        public int x //1. property
        {
            get{ return _x; }
            set{ _x = value; CoordinatesChanged(_x);}
        }
        public int y //1. property
        {
            get{ return _y; }
            set{ _y = value; CoordinatesChanged(_y);}
        }
        
        public readonly override string ToString() => $"({x}, {y})"; 
            //4. readonly override
        public event Action<int> CoordinatesChanged;
            //3. 이벤트
    }
    
  • 좌표가 변경 될 때 발생하는 CoordinatesChanged event 가 포함되어 있습니다.

  • 다음 예제는 이벤트 처리를 보여줍니다. xyCoordinatesChanged

    class Program
    {
        static void Main(string[] args) {
            Coordinate point = new Coordinate();   
            point.CoordinatesChanged += StructEventHandler;
            point.x = 10; point.y = 20;
        }
    
        static void StructEventHandler(int point) {
            Console.WriteLine("Coordinate changed to {0}", point);
        }
    }