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);
}

以下是一個建立包含字串和整數項的元組的示例。

示例

 線上演示

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-Jun-2020

760 次瀏覽

開啟您的 職業 生涯

完成課程獲得認證

開始
廣告
© . All rights reserved.