Tuple<T1,T2> 클래스

정의

2개의 요소로 구성된 튜플 또는 쌍을 나타냅니다.

generic <typename T1, typename T2>
public ref class Tuple : IComparable, System::Collections::IStructuralComparable, System::Collections::IStructuralEquatable
generic <typename T1, typename T2>
public ref class Tuple : IComparable, System::Collections::IStructuralComparable, System::Collections::IStructuralEquatable, System::Runtime::CompilerServices::ITuple
public class Tuple<T1,T2> : IComparable, System.Collections.IStructuralComparable, System.Collections.IStructuralEquatable
public class Tuple<T1,T2> : IComparable, System.Collections.IStructuralComparable, System.Collections.IStructuralEquatable, System.Runtime.CompilerServices.ITuple
[System.Serializable]
public class Tuple<T1,T2> : IComparable, System.Collections.IStructuralComparable, System.Collections.IStructuralEquatable
type Tuple<'T1, 'T2> = class
    interface IStructuralComparable
    interface IStructuralEquatable
    interface IComparable
type Tuple<'T1, 'T2> = class
    interface IStructuralComparable
    interface IStructuralEquatable
    interface IComparable
    interface ITuple
[<System.Serializable>]
type Tuple<'T1, 'T2> = class
    interface IStructuralEquatable
    interface IStructuralComparable
    interface IComparable
[<System.Serializable>]
type Tuple<'T1, 'T2> = class
    interface IStructuralEquatable
    interface IStructuralComparable
    interface IComparable
    interface ITuple
Public Class Tuple(Of T1, T2)
Implements IComparable, IStructuralComparable, IStructuralEquatable
Public Class Tuple(Of T1, T2)
Implements IComparable, IStructuralComparable, IStructuralEquatable, ITuple

형식 매개 변수

T1

튜플의 첫 번째 구성 요소 형식입니다.

T2

튜플의 두 번째 구성 요소 형식입니다.

상속
Tuple<T1,T2>
특성
구현

설명

튜플은 값의 특정 수와 시퀀스를 포함하는 데이터 구조입니다. 클래스는 Tuple<T1,T2> 두 개의 구성 요소가 있는 튜플인 2 튜플 또는 쌍을 나타냅니다. 2 튜플은 구조체와 KeyValuePair<TKey,TValue> 비슷합니다.

생성자 또는 정적 메서드를 Tuple<T1,T2> 호출하여 개체를 Tuple<T1,T2> 인스턴스화할 수 Tuple.Create<T1,T2>(T1, T2) 있습니다. 읽기 전용 Item1Item2 인스턴스 속성을 사용하여 튜플 구성 요소의 값을 검색할 수 있습니다.

튜플은 일반적으로 다음과 같은 네 가지 방법으로 사용됩니다.

  • 단일 데이터 집합을 나타냅니다. 예를 들어 튜플은 데이터베이스의 레코드를 나타낼 수 있으며 해당 구성 요소는 해당 레코드의 필드를 나타낼 수 있습니다.

  • 데이터 집합에 쉽게 액세스하고 조작할 수 있도록 합니다. 다음 예제에서는 학생 이름과 해당 시험 점수를 포함하는 개체의 배열 Tuple<T1,T2> 을 정의합니다. 그런 다음 배열을 반복하여 평균 테스트 점수를 계산합니다.

    using System;
    
    public class Example
    {
       public static void Main()
       {
          Tuple<string, Nullable<int>>[] scores = 
                        { new Tuple<string, Nullable<int>>("Jack", 78),
                          new Tuple<string, Nullable<int>>("Abbey", 92), 
                          new Tuple<string, Nullable<int>>("Dave", 88),
                          new Tuple<string, Nullable<int>>("Sam", 91), 
                          new Tuple<string, Nullable<int>>("Ed", null),
                          new Tuple<string, Nullable<int>>("Penelope", 82),
                          new Tuple<string, Nullable<int>>("Linda", 99),
                          new Tuple<string, Nullable<int>>("Judith", 84) };
          int number;
          double mean = ComputeMean(scores, out number);
          Console.WriteLine("Average test score: {0:N2} (n={1})", mean, number);
       }
    
       private static double ComputeMean(Tuple<string, Nullable<int>>[] scores, out int n) 
       {
          n = 0;      
          int sum = 0;
          foreach (var score in scores)
          {
             if (score.Item2.HasValue)
             { 
                n += 1;
                sum += score.Item2.Value;
             }
          }     
          if (n > 0)
             return sum / (double) n;
          else
             return 0;
       }
    }
    // The example displays the following output:
    //       Average test score: 87.71 (n=7)
    
    open System
    
    let scores = 
        [| Tuple<string, Nullable<int>>("Jack", 78)
           Tuple<string, Nullable<int>>("Abbey", 92) 
           Tuple<string, Nullable<int>>("Dave", 88)
           Tuple<string, Nullable<int>>("Sam", 91) 
           Tuple<string, Nullable<int>>("Ed", Nullable())
           Tuple<string, Nullable<int>>("Penelope", 82)
           Tuple<string, Nullable<int>>("Linda", 99)
           Tuple<string, Nullable<int>>("Judith", 84) |]
    
    let computeMean (scores: Tuple<string, Nullable<int>>[]) (n: int outref) = 
        n <- 0      
        let mutable sum = 0
        for _, score in scores do
            if score.HasValue then
                n <- n + 1
                sum <- sum + score.Value
        if n > 0 then
            double sum / double n
        else
            0
    
    let mutable number = 0
    let mean = computeMean scores &number
    printfn $"Average test score: {mean:N2} (n={number})"
    // The example displays the following output:
    //       Average test score: 87.71 (n=7)
    
    Module Example
       Public Sub Main()
          Dim scores() As Tuple(Of String, Nullable(Of Integer)) = 
                          { New Tuple(Of String, Nullable(Of Integer))("Jack", 78),
                            New Tuple(Of String, Nullable(Of Integer))("Abbey", 92), 
                            New Tuple(Of String, Nullable(Of Integer))("Dave", 88),
                            New Tuple(Of String, Nullable(Of Integer))("Sam", 91), 
                            New Tuple(Of String, Nullable(Of Integer))("Ed", Nothing),
                            New Tuple(Of String, Nullable(Of Integer))("Penelope", 82),
                            New Tuple(Of String, Nullable(Of Integer))("Linda", 99),
                            New Tuple(Of String, Nullable(Of Integer))("Judith", 84) }
          Dim number As Integer
          Dim mean As Double = ComputeMean(scores, number)
          Console.WriteLine("Average test score: {0:N2} (n={1})", mean, number)
       End Sub
       
       Private Function ComputeMean(scores() As Tuple(Of String, Nullable(Of Integer)), 
                                    ByRef n As Integer) As Double
          n = 0      
          Dim sum As Integer
          For Each score In scores
             If score.Item2.HasValue Then 
                n += 1
                sum += score.Item2.Value
             End If
          Next     
          If n > 0 Then
             Return sum / n
          Else
             Return 0
          End If             
       End Function
    End Module
    ' The example displays the following output:
    '       Average test score: 87.71 (n=7)
    
  • 매개 변수(C#) 또는 ByRef 매개 변수(Visual Basic)를 사용하지 out 않고 메서드에서 여러 값을 반환합니다. 예를 들어 다음 예제에서는 개체를 Tuple<T1,T2> 사용하여 정수 나누기에서 발생하는 몫과 나머지를 반환합니다.

    using System;
    
    public class Class1
    {
       public static void Main()
       {
          int dividend, divisor;
          Tuple<int, int> result;
          
          dividend = 136945; divisor = 178;
          result = IntegerDivide(dividend, divisor);
          if (result != null)
             Console.WriteLine(@"{0} \ {1} = {2}, remainder {3}", 
                               dividend, divisor, result.Item1, result.Item2);
          else
             Console.WriteLine(@"{0} \ {1} = <Error>", dividend, divisor);
                            
          dividend = Int32.MaxValue; divisor = -2073;
          result = IntegerDivide(dividend, divisor);
          if (result != null)
             Console.WriteLine(@"{0} \ {1} = {2}, remainder {3}", 
                               dividend, divisor, result.Item1, result.Item2);
          else
             Console.WriteLine(@"{0} \ {1} = <Error>", dividend, divisor);
       }
    
       private static Tuple<int, int> IntegerDivide(int dividend, int divisor)
       {
          try {
             int remainder;
             int quotient = Math.DivRem(dividend, divisor, out remainder);
             return new Tuple<int, int>(quotient, remainder);
          }   
          catch (DivideByZeroException) {
             return null;
          }      
       }
    }
    // The example displays the following output:
    //       136945 \ 178 = 769, remainder 63
    //       2147483647 \ -2073 = -1035930, remainder 757
    
    open System
    
    let integerDivide (dividend: int) divisor =
        try
            let quotient, remainder = Math.DivRem(dividend, divisor)
            Tuple<int, int>(quotient, remainder)
        with :? DivideByZeroException ->
            Unchecked.defaultof<Tuple<int, int>>
    
    [<EntryPoint>]
    let main _ =
        let dividend = 136945 
        let divisor = 178
        let result = integerDivide dividend divisor
        if box result <> null then
            printfn $@"{dividend} \ {divisor} = {result.Item1}, remainder {result.Item2}" 
        else
            printfn $@"{dividend} \ {divisor} = <Error>"
                        
        let dividend = Int32.MaxValue 
        let divisor = -2073
        let result = integerDivide dividend divisor
        if box result <> null then
            printfn $@"{dividend} \ {divisor} = {result.Item1}, remainder {result.Item2}" 
        else
            printfn $@"{dividend} \ {divisor} = <Error>"
        0
    // The example displays the following output:
    //       136945 \ 178 = 769, remainder 63
    //       2147483647 \ -2073 = -1035930, remainder 757
    
    Module modMain
       Public Sub Main()
          Dim dividend, divisor As Integer
          Dim result As Tuple(Of Integer, Integer)
          
          dividend = 136945 : divisor = 178
          result = IntegerDivide(dividend, divisor)
          If result IsNot Nothing Then
             Console.WriteLine("{0} \ {1} = {2}, remainder {3}", 
                               dividend, divisor, result.Item1, result.Item2)
          Else
             Console.WriteLine("{0} \ {1} = <Error>", dividend, divisor)
          End If
                            
          dividend = Int32.MaxValue : divisor = -2073
          result = IntegerDivide(dividend, divisor)
          If result IsNot Nothing Then
             Console.WriteLine("{0} \ {1} = {2}, remainder {3}", 
                               dividend, divisor, result.Item1, result.Item2)
          Else
             Console.WriteLine("{0} \ {1} = <Error>", dividend, divisor)
          End If
       End Sub
       
       Private Function IntegerDivide(dividend As Integer, divisor As Integer) As Tuple(Of Integer, Integer)
          Try
             Dim remainder As Integer
             Dim quotient As Integer = Math.DivRem(dividend, divisor, remainder)
             Return New Tuple(Of Integer, Integer)(quotient, remainder)
          Catch e As DivideByZeroException
             Return Nothing
          End Try      
       End Function
    End Module
    ' The example displays the following output:
    '       136945 \ 178 = 769, remainder 63
    '       2147483647 \ -2073 = -1035930, remainder 757
    
  • 단일 매개 변수를 통해 메서드에 여러 값을 전달합니다. 예를 들어 메서드에는 Thread.Start(Object) 시작 시 스레드가 실행되는 메서드에 하나의 값을 제공할 수 있는 단일 매개 변수가 있습니다. 개체를 Tuple<T1,T2> 메서드 인수로 제공하는 경우 스레드의 시작 루틴에 두 개의 데이터 항목을 제공할 수 있습니다.

생성자

Tuple<T1,T2>(T1, T2)

Tuple<T1,T2> 클래스의 새 인스턴스를 초기화합니다.

속성

Item1

현재 Tuple<T1,T2> 개체의 첫 번째 구성 요소 값을 가져옵니다.

Item2

현재 Tuple<T1,T2> 개체의 두 번째 구성 요소 값을 가져옵니다.

메서드

Equals(Object)

현재 Tuple<T1,T2> 개체가 지정된 개체와 같은지 여부를 나타내는 값을 반환합니다.

GetHashCode()

현재 Tuple<T1,T2> 개체에 대한 해시 코드를 반환합니다.

GetType()

현재 인스턴스의 Type을 가져옵니다.

(다음에서 상속됨 Object)
MemberwiseClone()

현재 Object의 단순 복사본을 만듭니다.

(다음에서 상속됨 Object)
ToString()

Tuple<T1,T2> 인스턴스의 값을 나타내는 문자열을 반환합니다.

명시적 인터페이스 구현

IComparable.CompareTo(Object)

현재 Tuple<T1,T2> 개체를 지정된 개체와 비교하고 현재 개체가 정렬 순서에 지정된 개체보다 이전인지, 이후인지 또는 같은 위치인지를 나타내는 정수를 반환합니다.

IStructuralComparable.CompareTo(Object, IComparer)

지정된 비교자를 사용하여 현재 Tuple<T1,T2> 개체와 지정된 개체를 비교하고 정렬 순서에서 현재 개체의 위치가 지정된 개체보다 앞인지, 뒤인지 또는 동일한지를 나타내는 정수를 반환합니다.

IStructuralEquatable.Equals(Object, IEqualityComparer)

지정된 비교 메서드를 기반으로 현재 Tuple<T1,T2> 개체가 지정된 개체와 같은지 여부를 나타내는 값을 반환합니다.

IStructuralEquatable.GetHashCode(IEqualityComparer)

지정된 계산 메서드를 사용하여 현재 Tuple<T1,T2> 개체에 대한 해시 코드를 계산합니다.

ITuple.Item[Int32]

지정한 Tuple 요소의 값을 가져옵니다.

ITuple.Length

Tuple의 요소 수를 가져옵니다.

확장 메서드

Deconstruct<T1,T2>(Tuple<T1,T2>, T1, T2)

2개 요소가 포함된 튜플을 개별 변수로 분해합니다.

ToValueTuple<T1,T2>(Tuple<T1,T2>)

Tuple 클래스 인스턴스를 ValueTuple 구조체 인스턴스로 변환합니다.

적용 대상

추가 정보