泛型List方法屬性

這兩天上課正好學泛型和ArrayList之間的區別,在家看了看深入理解和李志的學習筆記,感覺泛型內容很多,在深入理解中就佔了三四十頁,目前小懂的一些方法與大家分享~後續學習深入我還會補充

首先介紹一個List<T>的方法  AsReadOnly()   此方法返回的是一個只讀接口,實例:

            List<int> num = new List<int>();//首先創建一個泛型集合
            num.Add(1);//給集合中屬性賦值
            ...省略
            IList<int> bb = num.AsReadOnly();//這個方法代表返回一個ILis<T>t只讀接口
           // bb.Add(10); 顧名思義只讀數據就是隻能讀,不能寫。所以這行代碼是錯誤的 
            for (int x = 0; x < num.Count; x++)
            {
                Console.WriteLine(bb[x]);
            }
            /*輸出
             *1
             *2
             *3
             *4
             *5
             */

其中的一個方法 Count返回的是int類型的數據,該方法給出集合中項的個數,實例:

List<int> num = new List<int>();//首先創建一個泛型集合
            num.Add(1);//給集合中屬性賦值
            num.Add(2);
            num.Add(3);
            num.Add(4);
            num.Add(5);
            Console.WriteLine(num.Count); //返回的是int類型的參數,該屬性給出集合中項的個數     
            //打印結果  5   
其中的一個方法RemoveAt返回的是void類型的數據,該方法從結合中刪除索引index處的項(自定義角標)

            List<int> num = new List<int>();//首先創建一個泛型集合
            num.Add(1);//給集合中屬性賦值
            num.Add(2);
            num.Add(3);
            num.Add(4);
            num.Add(5);
            num.RemoveAt(0);//返回值void  會從集合中刪除編號(角標)爲0的項
            for (int x = 0; x < num.Count; x++)
            {
                Console.WriteLine(num[x]);//打印結果  2 3 4 5
            }
其中的一個方法Insert返回的是void類型的數據,該方法把值插入到集合指定的索引位置上

            List<int> num = new List<int>();//首先創建一個泛型集合
            num.Add(1);//給集合中屬性賦值
            num.Add(2);
            num.Add(3);
            num.Add(4);
            num.Add(5);
            num.Insert(3,666);//返回的是void類型,這句代碼意思就是把666插入角標爲3的位置,其他元素依次自動重新排序順移
          //結果 1 2 3 666 4 5
            for (int x = 0; x < num.Count; x++)
            {
                Console.WriteLine(num[x]);//打印結果  2 3 4 5
            }
其中的一個方法CopyTo返回的是void類型的數據,該方法把集合中的項複製到數組nums中,從數組的0角標開始複製

int[] nums = new int[5];//創建數組
            List<int> num = new List<int>();//首先創建一個泛型集合
            num.Add(1);//給集合中屬性賦值
            num.Add(2);
            num.Add(3);
            num.Add(4);
            num.Add(5);
            num.CopyTo(nums, 0);//該方法返回值類型爲void,把集合中的項複製到數組nums中,從數組的0角標開始複製
            for (int x = 0; x < nums.Length; x++)
            {
                Console.WriteLine("數組:" + nums[x]);//打印結果 數組:1 數組:2 ...  數組:5
            }
            for (int x = 0; x < num.Count; x++)
            {
                Console.WriteLine(num[x]);//打印結果 1 2 3 4 5
            }

...未完待續



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章