📜  C#|如何获得元组的第五元素?

📅  最后修改于: 2021-05-29 19:56:20             🧑  作者: Mango

元组是一种数据结构,它为您提供最简单的方式来表示一个数据集,该数据集具有多个可能/可能彼此不相关的值。 Item5属性用于获取给定元组的第五个元素。它不适用于1元组,2元组,3元组和4元组,但适用于所有其他其余元组。

句法:

public T5 Item5 { get; }

在此, T5是当前Tuple <>对象的第五个分量的值。该元组<>可以是5元组,6元组,7元组或8元组。

示例:在下面的代码中,您可以看到我们正在访问每个元组的第五个元素。

// C# program to illustrate how to get 
// the fifth element of the tuple
using System;
  
class GFG {
  
    // Main method
    static public void Main()
    {
  
        // Taking 5-tuple
        var st5 = Tuple.Create("Siya", 22, "EEE", 2017,
                                           "20-Mar-1993");
  
        Console.WriteLine("Student-5 DOB: " + st5.Item5);
  
        // Taking 6-tuple
        var st6 = Tuple.Create("Riya", 24, "ME", 2015,
                               "30-May-1991", 230134832);
  
        Console.WriteLine("Student-6 DOB: " + st6.Item5);
  
        // Taking 7-tuple
        var st7 = Tuple.Create("Rohit", 21, "IT", 2017, 
                        "21-Apr-1994", 384749829, 20000);
  
        Console.WriteLine("Student-7 DOB: " + st7.Item5);
  
        // Taking 8-tuple
        var st8 = Tuple.Create("Manita", 24, "CSE", 2013, 
                   "03-Aug-1991", 235678909, 34000, "C#");
  
        Console.WriteLine("Student-8 DOB: " + st8.Item5);
    }
}
输出:
Student-5 DOB: 20-Mar-1993
Student-6 DOB: 30-May-1991
Student-7 DOB: 21-Apr-1994
Student-8 DOB: 03-Aug-1991

注意:您还可以通过使用GetType()方法或使用Type.GetGenericArguments方法来获取元组的第五个组件的类型。

例子:

// C# program to illustrate how to get the 
// type of the fifth element of the tuple
using System;
   
class GFG{
       
    // Main method
    static public void Main (){
           
           
        // Taking 5-tuple
        var stu5 = Tuple.Create("Siya", 22, "CSE",2017,101);
        Console.WriteLine("Student-5 ID: "+stu5.Item5);
           
        // Get the type of Item5
        // Using GetType() method
        Console.WriteLine("Type of Item5: "+stu5.Item5.GetType());
           
        // Get the type of Item5
        // Using Type.GetGenericArguments method
        Type stu5type = stu5.GetType();
        Console.WriteLine("Type of Item5: "+stu5type.GetGenericArguments()[4]);
         
    }
}
输出:
Student-5 ID: 101
Type of Item5: System.Int32
Type of Item5: System.Int32