프로그래밍/C#

튜플이란? 튜플 사용법

gameObject 2023. 6. 23. 01:06
728x90

튜플

- 여러 필드를 담을 수 있는 구조체

- 데이터 형식이 따로 있는것은 아니며 ( )안에 2개이상의 필드를 지정함으로써 구성된다.

- 구조체로써 값 형식이다.

- 즉석에서 사용할 복합 데이터 형식을 선언할때 적합하다.

 

 static void tuple()
{
    //튜플 선언하는 법 : 그냥 값 두개가 덩그러니 놓여있다는것이 튜플이다.
    (int xPos, int yPos) playerPosition = (0, 1);

    //튜플 값 바꾸는법
    playerPosition.xPos = 10;
    playerPosition.yPos = 10;

    Console.WriteLine("player position: {0} {1}", playerPosition.xPos, playerPosition.yPos);

    //튜플 스왑하는 법  (playerPosition,yPos , playerPosition.xPos가 주소를 불러온게 아니라 그냥 값이라서 가능함)
    playerPosition.xPos = 10;
    playerPosition.yPos = 20;
    (playerPosition.xPos, playerPosition.yPos) = (playerPosition.yPos, playerPosition.xPos);
    Console.WriteLine("player position: {0} {1}", playerPosition.xPos, playerPosition.yPos);

}

 

var로도 선언을 해줄 수 있는데, 이렇게 할 경우 아래와 같이 item으로 순서가 먹여진다.

 

 

var로 선언해주면서 이름까지 명명해주기 위해서는 아래 처럼 해주면 됩니다.

var player = (first: 1, second: 2);
Console.WriteLine("{0} , {1} ",player.first,player.second);
//출력결과 1,2

이런식으로 이름을 명명해줄 수 있다.

 

 

어떤 함수 내부에서 여러가지 필드를 생성해주고 싶을때 쓰면 좋을것 같다는 생각이 든다.

728x90