10 구조체

vencott·2021년 6월 2일
0

C#

목록 보기
10/32

Value Type vs Reference Type

struct

Value Type의 데이터형을 정의한다

C# .NET의 기본 데이터형(int, double, bool 등)은 struct로 정의되어 있다

Value Type은 상속될 수 없으며 상대적으로 간단한 데이터 값을 저장하는데 사용된다

class

Reference Type의 데이터형을 정의한다

클래스는 상속이 가능하고 상대적으로 복잡한 데이터와 행위들을 정의하는데 사용된다

Value Type의 parameter 전달은 데이터를 복사(copy)하여 전달하는 반면 Reference Type의 전달은 Heap상의 객체에 대한 레퍼런스를 전달한다

// System.Int32 (Value Type)
public struct Int32 
{ 
   //....
}

// System.String (Reference Type)
public sealed class String 
{
   //....
}

struct 구조체

C# 개발을 할때 대부분 class를 사용하지만, 클래스보다 상대적으로 가벼운 오버헤드를 지닌 구조체가 필요할 때 struct를 사용해 구조체를 정의한다

C#의 구조체는 메소드, 프로퍼티 등 클래스와 거의 비슷한 구조를 지니고 있다

상속(Inheritance)은 불가능하지만 인터페이스(Interface) 구현은 가능하다

using System;

namespace MySystem
{
   class Program
   {
      // 구조체 정의
      struct MyPoint
      {
         public int X;
         public int Y;

         public MyPoint(int x, int y)
         {
            this.X = x;
            this.Y = y;
         }

         public override string ToString()
         {
            return string.Format("({0}, {1})", X, Y);
         }
      }

      static void Main(string[] args)
      {
         // 구조체 사용
         MyPoint pt = new MyPoint(10, 12);
         Console.WriteLine(pt.ToString());
      }
   }
}

출처: http://www.csharpstudy.com/

profile
Backend Developer

0개의 댓글