標籤:style blog color io os ar for 檔案 div
想要把泛型搞明白,最好先弄明白下面的代碼執行個體
本執行個體是建立了兩個類,然後在類中可以添加任意類型的值,並且可以利用foreach語句讀出
1 //第一個節點類,放在一個檔案中 2 using System; 3 using System.Collections.Generic; 4 using System.Linq; 5 using System.Text; 6 using System.Threading.Tasks; 7 using System.Collections; 8 9 namespace CommonGeneral 10 { 11 //編寫節點類,類型為object(在c#中所有的類型都是object 類的衍生類別) 12 //可以向本類中添加任何類型的值 13 //本類具有的屬性是next,prev,Value 14 public class LinkNode 15 { 16 public LinkNode(object value) 17 { 18 this.Value = value; 19 } 20 21 public object Value 22 { 23 get; 24 private set;//設定成private將不允許在類外用直接向本屬性賦值 25 //只允許在對象的初始化時賦值 26 } 27 public LinkNode next 28 { 29 get; 30 internal set;//internal修飾符約定在本程式集內的任何其他函數模組中 31 //都可以對它賦值。 32 } 33 public LinkNode prev 34 { 35 get; 36 internal set; 37 } 38 } 39 } 40 //第二個類,是對第一個類的調用和存取,建立鏈表, 41 //單獨放在一個檔案家中 42 using System; 43 using System.Collections.Generic; 44 using System.Linq; 45 using System.Text; 46 using System.Threading.Tasks; 47 using System.Collections; 48 49 namespace CommonGeneral 50 { 51 //IEnumberable介面是System.Collections命名空間下的一個程式介面 52 //下面是這個介面的函數 53 /* 54 namespace System.Collections 55 { 56 // 摘要: 57 // 公開枚舉數,該枚舉數支援在非泛型集合上進行簡單迭代。 58 public interface IEnumerable 59 { 60 // 摘要: 61 // 返回一個逐一查看集合的枚舉數。 62 // 63 // 返回結果: 64 // 一個可用於逐一查看集合的 System.Collections.IEnumerator 對象。 65 [DispId(-4)] 66 IEnumerator GetEnumerator(); 67 } 68 } 69 */ 70 class BigList:IEnumerable 71 { 72 public LinkNode Last { get; private set; } 73 public LinkNode First { get; private set; } 74 public LinkNode AddLast(object value) 75 { 76 var newnode = new LinkNode(value); 77 if(First==null) 78 { 79 First = newnode; 80 Last = newnode; 81 Last.next = null; 82 Last.prev = null; 83 } 84 else 85 { 86 Last.next = newnode; 87 newnode.prev = Last; 88 Last = newnode; 89 } 90 return newnode; 91 } 92 public IEnumerator GetEnumerator() 93 { 94 LinkNode current = First; 95 while(current!=null) 96 { 97 yield return current.Value; 98 current = current.next; 99 }100 }101 /* IEnumerator IEnumerable.GetEnumberator()102 {103 return GetEnumberator();104 }*/105 }106 }107 108 //------------主函數---------------109 using System;110 using System.Collections.Generic;111 using System.Linq;112 using System.Text;113 using System.Threading.Tasks;114 115 namespace CommonGeneral116 {117 class Program118 {119 static void Main(string[] args)120 {121 BigList list = new BigList();122 list.AddLast(100);123 list.AddLast("nihao");124 list.AddLast(true);125 list.AddLast("Any type value can add into this set");126 foreach(var value in list)127 {128 Console.WriteLine(value.ToString());129 }130 Console.ReadKey();131 return;132 }133 }134 }
C#學習之泛型準備