C# 4.0 中的元組是什麼?


元組包含一系列不同資料型別的元素。引入元組是為了返回 Tuple<T> 例項,而無需分別指定每個元素的型別。

讓我們建立一個包含兩個元素的元組。以下是宣告元組的方法。 −

Tuple<int, string>person = new Tuple <int, string>(32, "Steve");

現在,檢查元組中的第一個專案(該專案是一個整數) −

if (tuple.Item1 == 99) {
   Console.WriteLine(tuple.Item1);
}

現在檢查元組中的第二個專案(該專案是一個字串) −

if (tuple.Item2 == "Steve") {
   Console.WriteLine(tuple.Item2);
}

以下示例展示如何建立一個包含字串和 int 專案的元組 −

舉例

 現場演示

using System;
using System.Threading;

namespace Demo {
   class Program {

      static void Main(string[] args) {

         Tuple<int, string> tuple = new Tuple<int, string>(50, "Tom");

         if (tuple.Item1 == 50) {
            Console.WriteLine(tuple.Item1);
         }

         if (tuple.Item2 == "Jack") {
            Console.WriteLine(tuple.Item2);
         }
      }
   }
}

輸出

50

更新於: 20-6 月-2020

760 次瀏覽

開啟您的 職業生涯

完成課程即可獲得認證

開始學習
廣告
© . All rights reserved.