元組的概要: 數組合並了相同類型的對象,而元組合並了不同類型的對象。元組起源於函數編程語言(如F#) ,在 這些語言中頻繁使用元組。在N盯4中,元組可通過.NET Fmmework用於所有的NET語言。 .NET 4定義了8個泛型Tuple類和一個靜態Tuple類,它們用作元組的工廠。這里的不同泛型Tuple 類支持不同數量的元素。例如,Tuple<T1>包含-個元素,Tuple<T1,T2>包含兩個元素,以此類推。 1.第一個例子 private Tuple<int, int> Divide(int dividend, int divisor) { int result = dividend / divisor; int reminder = dividend % divisor; return Tuple.Create<int, int>(result, reminder); //返回兩個相同類型元素的元組 } --------測試------------- private void button1_Click(object sender, EventArgs e) { Tuple<int, int> result = Divide(13, 2); Console.WriteLine("result of divison:{0}," + "reminder:{1}", result.Item1, result.Item2); //用屬性item1,item2訪問元組的項 } -------結果------------- result of divison:6,reminder:1 2.第二個例子 private Tuple<int, string> MyTest2(int dividend, string Name) { int result = dividend / 2; string name = "Hello," + Name; return Tuple.Create<int, string>(result, name); //返回兩個不同類型元素的元組 } --------測試------------- private void button2_Click(object sender, EventArgs e) { Tuple<int, string> result = MyTest2(13, "limin"); Console.WriteLine("result of divison:{0}," + "Name:{1}", result.Item1, result.Item2); //用屬性item1,item2訪問元組的項 } -------結果------------- result of divison:6,Name:Hello,limin 3.第三個例子 如果元組包含的項超過8個,就可以使用帶8個參數的Tuple類定義。最后一個模板參數是TRest , 表示必須給它傳遞一個元組。這樣,就可以創建帶任意個參數的元組了。 下面說明這個功能: public class Tuple<T1,T2,T3,T4,T5,T6,T7,TRest> 其中,最后一個模板參數是一個元組類型,所以可以創建帶任意多項的元組: var tuple = Tuple.Create<string,string,string, int,int,int,double, Tuple<int,int>>( "stephanie","Alina","Nagel", 2009,6,2,1.37, Tuple.Create<int,int> (52,3490)); Tuple為何物? 什么是Tuple,在漢語上我們將其翻譯為元組。Tuple的概念源於數學概念,表示有序的數據集合。在.NET中Tuple被實現為泛型類型,n-Tuple表示有n個元素的Tuple,集合的元素可以是任何類型,例如定義一個3-Tuple表示Date(Year, Month, Day)時可以定義為: // Release : code01, 2009/05/29 // Author : Anytao, http://www.anytao.com var date = Tuple.Create<int, int, int>(2009, 5, 29); 優勢所在: 為方法實現多個返回值體驗,這是顯然的,Tuple元素都可以作為返回值。 靈活的構建數據結構,符合隨要隨到的公仆精神。 強類型。 不足總結: 當前Tuple類型的成員被實現為確定值,目前而言,還沒有動態決議成員數量的機制,如果你有可以告訴我:-) public class Tuple<T1, T2, T3, T4, T5, T6, T7, TRest>,可能引發ArgumentException。
