C# Tuple<T1,T2....T>元組的使用

來源:互聯網
上載者:User

標籤:

1)

先說組元:一個資料結構,由通過逗號分割的,用於傳遞給一個程式或者作業系統的一系列值的組合。

NET Framework 直接支援一至七元素的元組

Tuple<T1>Tuple<T1, T2>Tuple<T1, T2, T3>Tuple<T1, T2, T3, T4>Tuple<T1, T2, T3, T4, T5>Tuple<T1, T2, T3, T4, T5, T6>Tuple<T1, T2, T3, T4, T5, T6, T7>
此外,您可以通過嵌套的元組中的對象建立八個或多個元素的元組在Rest 屬性中的Tuple<T1, T2, T3, T4, T5, T6, T7, TRest> 對象。

簡單的樣本:
            //一個元素的元組            Tuple<int> test = new Tuple<int>(34);            //兩個元素的元組 1<n<8            Tuple<string, int> test2 = Tuple.Create<string, int>("str", 2);            Tuple<int, int> test2_1 = new Tuple<int, int>(2,2);            //8個元素的元組(注意,Tuple<類型...>: 基本"類型"最多7個, 第八個元素類型必須也為元組)            Tuple<int, int, int, int, int, int, int, Tuple<int>> test3 =             new Tuple<int, int, int, int, int, int, int, Tuple<int>>(1, 2, 3, 4, 5, 6, 7, new Tuple<int>(8));                        //也可以這樣            Tuple<int, int, Tuple<int, int>> test_i_i_Tii = new Tuple<int, int, Tuple<int, int>>(1,1,new Tuple<int,int>(2,3));                        Console.WriteLine(test.Item1);            Console.WriteLine(test2.Item1 + test2.Item2);            Console.WriteLine(test2_1.Item1 + test2_1.Item2);            Console.WriteLine(test3.Item1 + test3.Item2 + test3.Item3 + test3.Item4 + test3.Item5 + test3.Item6 + test3.Item7 + test3.Rest.Item1);
結果:


2)多個返回值問題
一般我們都是用out關鍵字(相比其他語言,如golang,out關鍵字還是稍微有點麻煩),此時我們可以使用元組實現:
namespace TupleDemo{    class Program    {        static void Main(string[] args)        {            //使用out拿到多個傳回值            string outparam = "";            int returnvalue = FunOutParamDemo(out outparam);            Console.WriteLine(returnvalue + "    " + outparam);            //使用元組拿到多個傳回值            Tuple<int, string> r = FunTupleParamDemo();            Console.WriteLine(r.Item1 + "    " + r.Item2);            Console.Read();        }        /// <summary>        /// out關鍵字,實現返回兩個傳回值        /// </summary>        /// <param name="o"></param>        /// <returns></returns>        public static int FunOutParamDemo(out string o)        {            o = "returnValue";            return 10;        }        /// <summary>        /// 使用元組實現【間接】返回【兩個】傳回值        /// </summary>        /// <returns></returns>        public static Tuple<int, string> FunTupleParamDemo() {            return new Tuple<int, string>(10, "returnValue");        }    }}
運行結果:



C# Tuple<T1,T2....T>元組的使用

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.