在 Csharp 中使用元组

发布日期:2026-07-14 02:24:03   来源 : 杭州电子商务研究院    浏览量 :12
杭州电子商务研究院 发布日期:2026-07-14 02:24:03  
12

介绍

C# 中的“元组”一词指的是可能由多个部分组成的数据结构。此数据结构可能是也可能不是具有多个值的数据集。元组最初是在 .NET Framework 4.0 中引入的,它们最多允许 8 个元素。超过这个数目将导致编译器错误。当您想要创建一个包含对象及其属性的数据结构,并且不想创建单独的类型时,可以使用元组。

元组的通用语法:

      Tuple<T1, T2, T3, T4, T5, T6, T7, TRest>
    

元组的特征

元组有几个优点。它们允许:

  1. 单个数据集中的多种数据类型
  2. 创建/操作和访问数据集
  3. 不使用out 的方法返回多个值
  4. 存储重复元素
  5. 使用单个参数将多个值传递给方法

在使用元组之前,我们有三个选项可以从方法返回多个值。我们可以使用ClassStruct类型,或者可以使用out参数。

元组还非常适合存储最多 8 个计数的对象属性,因为它们允许放置在其中的项目属于不同类型。例如,对于列表或数组,这项任务很困难,因为它们可以存储的元素数量没有限制,但类型限制了选项。例如,我们公司处理注册的 Web 应用程序中使用了元组,我们需要新来者提供 8 个元素。

创建元组

有两种方法可以利用元组数据结构。一种是基于类的方法,它利用Tuple<T>类的构造函数,另一种是Create方法,这也是一种可行的选择。

基于类的方法

我们可以利用Tuple<T>类来创建具有我们想要存储的元素的特定长度和类型的元组。

我们来看一个基于代码的例子。

      using System;

namespace tuples
{   
    class Tupling
    {
        static void Main(string[] args)
        {
            Tuple<string> MyStringTuple = new Tuple<string>("Pluralsight");
            Tuple<string,int> MyCustomTuple = new Tuple<string,int>("Daniel",28);
            Tuple<int, int, int, int, int, int, int, Tuple<int>> MyMaxTuple = new Tuple<int, int, int, int, int, int, int, Tuple<int>>(1, 2, 3, 4, 5, 6, 7, new Tuple<int>(8));
            Console.WriteLine($"The {nameof(MyStringTuple)} has the following elements: {MyStringTuple}");
            Console.WriteLine($"The {nameof(MyCustomTuple)} has the following elements: {MyCustomTuple}");
            Console.WriteLine($"The {nameof(MyMaxTuple)} has the following elements: {MyMaxTuple}");
            Console.ReadKey(); ;
        }
    }
}
    

让我们检查一下输出。

      The MyStringTuple has the following elements: (Pluralsight)
The MyCustomTuple has the following elements: (Daniel, 28)
The MyMaxTuple has the following elements: (1, 2, 3, 4, 5, 6, 7, 8)
    

从初始化中可以看出,我们有三个元组。一个是MyStringTuple,另一个是MyCustomTuple,最后是MyMaxTuple。它们都是唯一的,并提供了有关元组的所有信息。当您有一个包含 8 个项目的元组时,最后一个项目必须始终是元组。

创建方法

当您使用基于构造函数的方法时,它会使您的代码更难阅读,因为您必须为元组指定每个元素的类型,并且元组越长,它就越会淹没您的代码。为了减轻开发人员的痛苦,Tuple类诞生了create方法。它包含静态方法,允许您创建实例而无需提供每个元素的类型。

我们之前用这种风格重写的例子如下所示。

      using System;

namespace tuples
{   
    class Tupling
    {
        static void Main(string[] args)
        {
            var MyStringTuple = Tuple.Create("Pluralsight");
            var MyCustomTuple = Tuple.Create("Daniel",28);
            var MyMaxTuple = Tuple.Create(1, 2, 3, 4, 5, 6, 7, Tuple.Create(8));
            Console.WriteLine($"The {nameof(MyStringTuple)} has the following elements: {MyStringTuple}");
            Console.WriteLine($"The {nameof(MyCustomTuple)} has the following elements: {MyCustomTuple}");
            Console.WriteLine($"The {nameof(MyMaxTuple)} has the following elements: {MyMaxTuple}");
            Console.ReadKey();
        }
    }
}
    

这看起来更简洁,并可以提高下一个使用该应用程序的开发人员的可读性。

访问项目

当我们通过基于类的方法或 create 方法实例化一个新的元组时,我们的元组将具有一个唯一属性。它将使用以下逻辑将每个连续元素分配给实例的一个属性:

      Item<elementNumber>
    

这意味着具有 4 个元素的元组将具有以下属性:

      Tuple.Item1
Tuple.Item2
Tuple.Item3
Tuple.Item4
    

然后我们根据这个修改我们的代码:

      using System;
namespace tuples
{   
    class Tupling
    {
        static void Main(string[] args)
        {
            var MyStringTuple = Tuple.Create("Pluralsight");
            var MyCustomTuple = Tuple.Create("Daniel",28);
            var MyMaxTuple = Tuple.Create(1, 2, 3, 4, 5, 6, 7, Tuple.Create(8));                
            Console.WriteLine($"The first element of our {MyStringTuple} is {MyStringTuple.Item1}");
            Console.WriteLine($"The first element of our {MyCustomTuple} is {MyCustomTuple.Item1}, the second is: {MyCustomTuple.Item2}");
            Console.WriteLine($"The first element of our {MyMaxTuple} is {MyMaxTuple.Item1}, the last is: {MyMaxTuple.Rest}");
	        Console.ReadKey();
        }
    }
}
    

这给了我们以下输出:

      The first element of our (Pluralsight) is Pluralsight
The first element of our (Daniel, 28) is Daniel, the second is: 28
The first element of our (1, 2, 3, 4, 5, 6, 7, (8)) is 1, the last is: ((8))
    

请注意,八个对象元组的最后一个元素只能被称为.Rest,并且它必须始终是一个元组。

嵌套元组

通过将元组相互嵌套可以克服最多八个元素的限制。最佳做法是在最后一个元素处将一个元组嵌套到另一个元组中。但是,这并非强制要求,因此您可以将一个元组嵌套在另一个元组内的任何位置。当您在末尾嵌套时,您可以通过.Rest属性访问嵌套的元组;否则,您需要使用.Item<value>属性来访问元组。

我们用代码来演示一下。

      using System;

namespace tuples
{   
    class Tupling
    {
        static void Main(string[] args)
        {
        var MyMaxTupleNested = Tuple.Create(1, 2, 3, 4, 5, 6, 7, Tuple.Create(8, 9, 10, 11, 12, 13, 14, Tuple.Create(15, 16, 17, 18, 19, 20, 21)));
        Console.WriteLine($"My original tuple: {MyMaxTupleNested}");
        Console.WriteLine($"First element of the outest tuple: {MyMaxTupleNested.Item1}");
        Console.WriteLine($"First level of nesting: {MyMaxTupleNested.Rest.Item1}");
        Console.WriteLine($"Second level of nesting: {MyMaxTupleNested.Rest.Item1.Rest.Item1}");
        Console.ReadKey();
        }
    }
}
    

输出应如下所示:

      My original tuple: (1, 2, 3, 4, 5, 6, 7, (8, 9, 10, 11, 12, 13, 14, (15, 16, 17, 18, 19, 20, 21)))
First element of the outest tuple: 1
First level of nesting: (8, 9, 10, 11, 12, 13, 14, (15, 16, 17, 18, 19, 20, 21))
Second level of nesting: (15, 16, 17, 18, 19, 20, 21)
    

我认为,在最后一个元素处嵌套的方法提供了清晰的代码和清晰的故障排除方法。然而,这可能不是一种万能的方法,因为在某些情况下,在中间嵌套可能会更好。

结论

在本指南中,我们首先熟悉了元组,这是一种自 .NET 4.0 以来就成为 C# 一部分的数据结构。然后,我们研究了创建此类的新实例的两种不同方法,并学习了如何访问此数据结构的元素。最后,我们介绍了一些嵌套和有关如何提高效率的其他技巧。我希望这对您有所帮助,并希望您找到所需的内容。感谢您的阅读。

以上内容来自杭州电子商务研究院推送
关注
关于我们
热门推荐
合作伙伴
免责声明:本站部分资讯来源于网络,如有侵权请及时联系客服,我们将尽快处理
Copyright © 2025-2027 ToB产业网址导航 公安备案 浙公网安备33010602013138号 浙ICP备16025413号-9
支持 反馈 关注 数据