📌  相关文章
📜  获取表示ValueTuple值的字符串<T1,T2>C#中的实例

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

ValueTuple是C#7.0中引入的结构,表示值类型Tuple。它允许您存储一个数据集,该数据集包含可能彼此相关或不相关的多个值。您还可以在ToString方法的帮助下获得一个表示ValueTuple对象值的字符串。
此方法返回一个字符串,它将表示ValueTuple 对象的值。此方法表示的字符串采用(Item1,Item2)的形式,此处Item1和Item2表示Item1和Item2属性的值,并且如果任何属性包含空值,它将表示String.Empty

句法:

public override string ToString ();

返回类型:此方法的返回类型为System.String 。因此,它将返回一个表示ValueTuple 对象的字符串。

范例1:

// C# program to illustrate 
// the use of ToString method
using System;
  
namespace exampleofvaluetuple{
      
    class GFG {
          
        // Main Method
        static void Main(string[] args)
        {
            // 1-ValueTuple
            var v1 = ValueTuple.Create("Rina");
              
            // Get the value of ValueTuple
            // With the help of ToString method
            Console.WriteLine("ValueTuple 1: " + v1.ToString());
  
            // 2-ValueTuple
            var v2 = ValueTuple.Create("Rohan", 25);
              
            // Get the value of ValueTuple
            // With the help of ToString method
            Console.WriteLine("ValueTuple 2: " + v2.ToString());
        }
    }
}
输出:
ValueTuple 1: (Rina)
ValueTuple 2: (Rohan, 25)

范例2:

// C# program to illustrate 
// the use of ToString method
using System;
   
namespace exampleofvaluetuple {
      
    class GFG{
          
        // Main Method
        static void Main(string[] args)
        {
            // Nested Value Tuples
            var Emp1 = (Name:"Anu", Age: 23, Languages:ValueTuple.Create("C++",
                                                      "Java", "Python", "C#"));
   
            var Emp2 = (Name:"Boond", Age:27, Post: "Junior Engineer",
                          Languages:ValueTuple.Create("C++", "Java"));
   
            var Emp3 = (Name: "Rohit", Age: 25, Post: "HR", 
                        Languages: ValueTuple.Create("C++", 
                                            "Java", "C#"));
   
   
            var Emp4 = (Name: "Mohan", Age: 26, Post: "Junior Engineer",
                 Languages: ValueTuple.Create("C++", "Java", "Python"));
   
   
            // Get the value of Nested ValueTuples
            // With the help of ToString method
            Console.WriteLine("NValueTuple 1: {0}", Emp1.ToString());
            Console.WriteLine("NValueTuple 2: {0}", Emp2.ToString());
            Console.WriteLine("NValueTuple 3: {0}", Emp3.ToString());
            Console.WriteLine("NValueTuple 4: {0}", Emp4.ToString());
   
   
        }
    }
}
输出:
NValueTuple 1: (Anu, 23, (C++, Java, Python, C#))
NValueTuple 2: (Boond, 27, Junior Engineer, (C++, Java))
NValueTuple 3: (Rohit, 25, HR, (C++, Java, C#))
NValueTuple 4: (Mohan, 26, Junior Engineer, (C++, Java, Python))