[C# 문법] C# ValueTuple

참조



ValueTuple

  • C# 7.0(.NET Framework 4.7)에는 Tuple의 값 형식 표현인 ValueTuple 구조가 도입되었습니다.
  • ValueTuple은 .NET Framework 4.7에서만 사용할 수 있습니다. 프로젝트에 ValueTuple이 표시되지 않으면 ValueTuple을 설치해야 합니다. (.NET Framework 4.7 이상 또는 .NET Standard Library 2.0 이상에는 이미 ValueTuple이 포함되어 있습니다.)


ValueTuple Initialization

  • ValueTuple을 생성하고 초기화하는 것은 쉽습니다.
  • 괄호()를 사용하고 그 안에 값을 지정하여 생성 및 초기화할 수 있습니다.
using System;

namespace ValueTupleTest
{
    class Program
    {
        static void Main(string[] args)
        {
            var person = (1, "Bill", "Gates");

            //equivalent Tuple
            //var person = Tuple.Create(1, "Bill", "Gates");
        }
    }
}
  • ValueTuple은 아래와 같이 각 요소의 유형을 지정하여 초기화할 수도 있습니다.
using System;

namespace ValueTupleTest
{
    class Program
    {
        static void Main(string[] args)
        {
            ValueTuple<int, string, string> person = (1, "Bill", "Gates");

            Console.WriteLine($"{person.Item1}, {person.Item2}, {person.Item3}");
        }
    }
}
  • 다음은 각 멤버에 대한 형식을 선언하는 간단한 방법입니다.
using System;

namespace ValueTupleTest
{
    class Program
    {
        static void Main(string[] args)
        {
            (int, string, string) person = (1, "Bill", "Gates");

            Console.WriteLine($"{person.Item1}, {person.Item2}, {person.Item3}");
        }
    }
}
  • 위의 튜플 초기화 문에서 var를 사용하지 않았음을 주목하십시오. 대신 대괄호 안에 각 멤버 값의 유형을 제공했습니다.
  • 튜플에는 두 개 이상의 값이 필요합니다. 다음은 튜플이 아닙니다.
var number = (1);  // int type, NOT a tuple
var numbers = (1,2); //valid tuple
  • Tuple과 달리 ValueTuple은 8개 이상의 값을 포함할 수 있습니다.
var numbers = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14); 

Named Members

  • Item1, Item2 등과 같은 기본 속성 이름을 사용하는 대신 ValueTuple 속성에 이름을 할당할 수 있습니다.
using System;

namespace ValueTupleTest
{
    class Program
    {
        static void Main(string[] args)
        {
            (int Id, string FirstName, string LastName) person = (1, "Bill", "Gates");

            Console.WriteLine($"{person.Id}, {person.FirstName}, {person.LastName}");
        }
    }
}
  • 아래와 같이 값이 있는 멤버 이름을 오른쪽에 할당할 수도 있습니다.
var person = (Id:1, FirstName:"Bill", LastName: "Gates");
  • 왼쪽 또는 오른쪽에 회원 이름을 제공할 수 있지만 양쪽에는 제공할 수 없습니다. 왼쪽이 오른쪽보다 우선합니다. 다음은 오른쪽에 있는 이름을 무시합니다.
// PersonId, FName, LName will be ignored.
(int Id, string FirstName, string LastName) person = (PersonId:1, FName:"Bill", LName: "Gates");

// PersonId, FirstName, LastName will be ignored. It will have the default names: Item1, Item2, Item3.
(string, string, int) person = (PersonId:1, FName:"Bill", LName: "Gates");
  • 변수를 멤버 값으로 할당할 수도 있습니다.
string firstName = "Bill", lastName = "Gates";
var per = (FirstName: firstName, LastName: lastName);


ValueTuple as Parameter

  • ValueType은 매개변수 유형 또는 메소드의 리턴 유형일 수도 있습니다. 다음 메소드는 ValueTuple 유형 매개변수를 허용합니다.
using System;

namespace ValueTupleTest
{
    class Program
    {
        static void Main(string[] args)
        {
            DisplayTuple((1, "Bill", "Gates"));
        }

        static void DisplayTuple((int, string, string) person)
        {
            Console.WriteLine("{0}, {1}, {2}", person.Item1, person.Item2, person.Item3);
        }
    }
}
  • 다음은 메서드에서 ValueTuple을 반환합니다.
using System;

namespace ValueTupleTest
{
    class Program
    {
        static void Main(string[] args)
        {
            var person = GetPerson();
            Console.WriteLine($"{person.Item1}, {person.Item2}, {person.Item3}");
        }

        static (int, string, string) GetPerson()
        {
            return (1, "Bill", "Gates");
        }
    }
}
  • 메서드에서 반환된 ValueTuple의 멤버 이름을 지정할 수도 있습니다.
using System;

namespace ValueTupleTest
{
    class Program
    {
        static void Main(string[] args)
        {
            var person = GetPerson();
            Console.WriteLine("{0}, {1}, {2}", person.Id, person.FirstName, person.LastName);
        }

        static (int Id, string FirstName, string LastName) GetPerson()
        {
            return (Id: 1, FirstName: "Bill", LastName: "Gates");
        }
    }
}


Deconstruction

  • ValueTuple의 개별 멤버는 분해하여 검색할 수 있습니다.
  • 분해 선언 구문은 ValueTuple을 부분으로 분할하고 해당 부분을 개별적으로 새로운 변수에 할당합니다.
using System;

namespace ValueTupleTest
{
    class Program
    {
        static void Main(string[] args)
        {
            // change property names
            (int PersonId, string FName, string LName) = GetPerson();
        }

        static (int, string, string) GetPerson()
        {
            return (Id: 1, FirstName: "Bill", LastName: "Gates");
        }
    }
}
  • 명시적 데이터 유형 이름 대신 var를 사용할 수도 있습니다.
static void Main(string[] args)
{
    // use var as datatype
    (var PersonId, var FName, var LName) = GetPerson();
}
static (int, string, string) GetPerson() 
{
    return (Id:1, FirstName: "Bill", LastName: "Gates");
}
  • ValueTuple은 또한 사용하지 않을 구성원에 대해 해체 시 "폐기"를 허용합니다.
using System;

namespace ValueTupleTest
{
    class Program
    {
        static void Main(string[] args)
        {
            // use discard _ for the unused member LName
            (var id, var FName, _) = GetPerson();
        }

        static (int, string, string) GetPerson()
        {
            return (Id: 1, FirstName: "Bill", LastName: "Gates");
        }
    }
}


728x90

이 글을 공유하기

댓글

Designed by JB FACTORY