內容摘錄 《Exploring Advanced Features in C# 探索C#中的高級特性》
1 public class TupleExample 2 { 3 4 public (string guitarType,int stringCount) GetGuitarType() 5 { 6 return ("Les Paul Studio" , 6); 7 } 8 }
1 using System; 2 3 namespace CharpinFocus 4 { 5 6 7 class Program 8 { 9 10 public enum InstrumentType {guitar, cello , violin}; 11 12 static void Main(string[] args) 13 { 14 TupleExample te = new TupleExample(); 15 16 var guitarResult = te.GetGuitarType(); 17 18 Console.WriteLine($"guitarResult.Item1 -> {guitarResult.Item1}"); 19 Console.WriteLine($"guitarResult.Item2 -> {guitarResult.Item2}"); 20 21 //Changing the Default Positional Names for Tuple Values 22 Console.WriteLine($"guitarResult.guitarType -> {guitarResult.guitarType}"); 23 Console.WriteLine($"guitarResult.stringCount -> {guitarResult.stringCount}"); 24 25 26 //Discrete tuple variables 解構元組 27 //Create Local Tuple Variables in the Return Data 28 (string gType, int iCount) = te.GetGuitarType(); 29 30 Console.WriteLine($"result gType -> {gType}"); 31 Console.WriteLine($"result iCount -> {iCount}"); 32 33 34 //Implicitly typed variables using var 35 var (BrandType, GuitarStringCount) = te.GetGuitarType(); 36 Console.WriteLine($"var BrandType -> {BrandType}"); 37 Console.WriteLine($"var GuitarStringCount -> {GuitarStringCount}"); 38 39 //Using var with some of the variables 40 (string bType , var sCount) = te.GetGuitarType(); 41 Console.WriteLine($"bType -> {bType}"); 42 Console.WriteLine($"sCount -> {sCount}"); 43 44 //Instances of Tuple Variables 45 PlayInstrument(guitarResult); 46 47 48 //---------- 比較元組 ----------- 49 // 50 //您還可以比較元組成員。 為了說明這一點,讓我們呆在樂器上,比較一下吉他和小提琴的弦數。 51 //首先使用您先前創建的枚舉,然后創建以下元組類型變量。 52 53 (string typeOfInstrument,int numberOfStrings) instrument1 = (nameof(InstrumentType.guitar),6); 54 55 (string typeOfInstrument,int numberOfStrings) instrument2 = (nameof(InstrumentType.violin),4); 56 57 58 //從C# 7.3開始檢查計數是否相等與使用if語句一樣容易。 59 //您還可以將整個元組變量相互比較。 60 if (instrument1 != instrument2) 61 { 62 Console.WriteLine("instrument1 != instrument2"); 63 } 64 65 if (instrument1.numberOfStrings != instrument2.numberOfStrings) 66 { 67 Console.WriteLine($"A {instrument2.typeOfInstrument} does not have the same number of strings as a {instrument1.numberOfStrings}"); 68 } 69 70 //在C#7.3之前比較元組,檢查用於要求Equals方法的元組相等性。 71 //如果您嘗試將==或!=與元組類型一起使用,則會看到錯誤 72 if (!instrument1.Equals(instrument2)) 73 { 74 Console.WriteLine("we are dealing with different instruments here."); 75 } 76 77 78 } 79 80 //Instances of Tuple Variables #1 81 //C#7允許您將元組用作實例變量。 這意味着您可以將變量聲明為元組。 82 //為了說明這一點,首先創建一個名為PlayInstrument的方法,該方法接受一個元組作為參數。 83 //這一切將只輸出一行文本。 84 static void PlayInstrument((string instrType,int strCount) instrumentToPlay) 85 { 86 Console.WriteLine($"I am playing a {instrumentToPlay.instrType} with {instrumentToPlay.strCount} strings."); 87 } 88 89 90 } 91 }