구조체 형식?

사용자 정의 형식

 

데이터와 관련 기능을 캡슐화할 수 있는 값 형식

 

동작을 거의 제공하지 않거나 작은 데이터 중심 형식을 설계하는데 사용 권장

 

struct 키워드를 사용하여 정의

 

https://www.youtube.com/watch?v=zL5rb-Q5WzE&list=PLTFRwWXfOIYBmr3fK17E0VhKPyYrGy75z&index=41

 

 

 

 

인스턴스는 new 키워드사용

모든 구조체 형식은 하나 이상의 생성자를 갖는다.

 

 

 

※클래스와 다른점

1. 값형식

2. 상속 불가능

 

매개변수 없는 생성자를 포함 불가

 

맴버 메서드에 virtual, protected 사용 불가

 

유형의 인스턴스가 작고 일반적으로 수명이 짧거나 다른 개체에 포함되는 경우

클래스 대신 구조체를 사용하는 것을 고려

 

다른 모든 경우는 클래스를 사용하자

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Stet39
{
 
    internal class Program
    {
        static void Main(string[] args)
        {
            //Position pos = new Position(1,1);
            //Position pos = new Position();
            //Position pos;
            //pos.x = 1;
            //pos.y = 1;
            //Console.WriteLine(pos);
            //Position pos = new Position(1,1);
            //pos.SetOrigin();
            //Console.WriteLine("{0}, {1}", pos.x, pos.y);

            Marine marine = new Marine(new Position(1,1));
            Console.WriteLine("마린의 현재 위치 : {0}, {1}", marine.position.x, marine.position.y); ;

            marine.Move(new Position(2, 3));
            Position pos = marine.GetPostion();
            Console.WriteLine("마린의 현재 위치 : {0}, {1}", pos.x, pos.y);

        }
    }
}

 

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Stet39
{
    struct Position
    {
        public int x;
        public int y;

        public Position(int x, int y)//매개 변수 없는 생성자 사용불가
        {
            this.x = x;
            this.y = y;
        }

        public void SetOrigin()
        {
            this.x = 0;
            this.y = 0;
        }
    }
}

 

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Stet39
{
    internal class Marine
    {
        public Position position;
        public Marine(Position position)
        {
            this.position = position;
        }
        public void Move(Position targetPosition)
        {
            Console.WriteLine("{0}, {1}로 이동합니다", targetPosition.x, targetPosition.y);
            this.position = targetPosition;
        }

        public Position GetPostion()
        {
            return this.position;
        }
    }
}

'Study > C#' 카테고리의 다른 글

[C#] 업캐스팅, 다운캐스팅  (0) 2024.06.13
[C#] 생성자 연결  (0) 2024.06.12
[C#] virtual, override  (0) 2024.06.12
[C#] 상속  (1) 2024.06.03
[C#] static 한정자  (0) 2024.06.02

+ Recent posts