📅  最后修改于: 2020-11-01 03:08:52             🧑  作者: Mango
C#元组是一种数据结构,用于存储元素序列。具有n个元素的元组称为n元组。
出于以下原因,我们可以使用Tuple。
在C#中,元组是一个包含静态方法的类。这些方法用于创建元组对象。以下是Tuple类的语法。
public static class Tuple
下表包含Tuple类的方法。
Method name | Description |
---|---|
Create |
It is used to create a new 1-tuple, or singleton. |
Create |
It is used to create a new 2-tuple, or pair. |
Create |
It is used to create a new 3-tuple, or triple. |
Create |
It is used to create a new 4-tuple, or quadruple. |
Create |
It is used to create a new 5-tuple, or quintuple. |
Create |
It is used to create a new 6-tuple, or sextuple. |
Create |
It is used to create a new 7-tuple, or septuple. |
Create |
It is used to create a new 8-tuple, or octuple. |
让我们看一个创建元组来存储图书信息的示例。在这里,我们在不使用静态方法的情况下创建Tuple。
using System;
namespace CSharpFeatures
{
class TupleExample
{
public static void Main(string[] args)
{
// Creating Tuple of three values
var book = new Tuple("C# in Depth", "Jon Skeet", 100.50);
Console.WriteLine("-----------------Book's Record---------------------");
Console.WriteLine("Title " + book.Item1);
Console.WriteLine("Author " + book.Item2);
Console.WriteLine("Price " + book.Item3);
}
}
}
输出:
-----------------Book's Record---------------------
Title C# in Depth
Author Jon Skeet
Price 100.5
我们可以使用Tuple类的静态方法来创建Tuple。在下面的示例中,我们使用create方法。
using System;
namespace CSharpFeatures
{
class TupleExample
{
public static void Main(string[] args)
{
// Creating Tuple using helper method (Create)
var book = Tuple.Create("C# in Depth", "Jon Skeet", 100.50);
Console.WriteLine("-----------------Book's Record---------------------");
Console.WriteLine("Title " + book.Item1);
Console.WriteLine("Author " + book.Item2);
Console.WriteLine("Price " + book.Item3);
}
}
}
输出:
-----------------Book's Record---------------------
Title C# in Depth
Author Jon Skeet
Price 100.5
我们可以使用元组从一个方法返回多个值。在下面的示例中,我们将元组返回给调用方方法。
using System;
namespace CSharpFeatures
{
public class Student
{
public static void Main(string[] args)
{
var (name,email) = Show();
Console.WriteLine(name+" "+email);
}
static (string name, string email) Show()
{
return ("irfan","irfan@gmail.com");
}
}
}