C#中動態(tài)數(shù)組用法實例
更新時間:2015年04月28日 14:24:27 作者:heishui
這篇文章主要介紹了C#中動態(tài)數(shù)組用法,實例分析了C#中ArrayList實現(xiàn)動態(tài)數(shù)組的技巧,非常具有實用價值,需要的朋友可以參考下
本文實例講述了C#中動態(tài)數(shù)組用法。分享給大家供大家參考。具體分析如下:
ArrayList是一種動態(tài)數(shù)組,其容量可隨著我們的需要自動進行擴充.
ArrayList位于System.Collections命名空間中,所以我們在使用時,需要導入此命名空間.
下面,我們還是在Student類的基礎上利用ArrayList操作,從而了解ArrayList的用法
public class Student { public Student(){} public Student(String name,int age,String hobby) { this.Name = name; this.Age = age; this.Hobby = hobby; } private String name; public String Name { get{return name;} set{name = value;} } private int age; public int Age { get{return age;} set{age = value;} } private String hobby; public String Hobby { get{return hobby;} set{hobby = value;} } public void say() { Console.WriteLine("大家好,我是'{0}',今年{1}歲,我喜歡'{2}'", this.Name,this.Age,this.Hobby); } }
編寫測試類,了解ArrayList的方法
using System.Collections; public class TestStudent { public static void main(String args []) { //建立ArrayList對象 ArrayList students = new ArrayList(); //實例化幾個Student類對象 Student rose = new Student("rose",25,"reading"); Student jack = new Student("jack",28,"singing"); Student mimi = new Student("mimi",26,"dancing"); //利用ArrayList類的add()方法添加元素 students.add(rose); students.add(jack); students.add(mimi); //利用ArrayList的Count屬性查看該集合中的元素數(shù)量 int number = students.Count; Console.WriteLine("共有元素" + number + "個"); //讀取單個元素,因為存入ArrayList中的元素會變?yōu)镺bject類型, //所以,在讀取時間, Student stu = students[0] as Student; stu.say(); //遍歷元素 -- 通過索引 for(int i = 0;i < students.Count;i ++) { Student a = students[i] as Student; a.say(); } //利用foreach循環(huán) foreach(Object o in students) { Student b = o as Student; b.say(); } //刪除元素 通過索引刪除 students.removeAt(0); //刪除元素, 通過對象名 students.remove(jack); //清空元素 students.Clear(); //我們知道,ArrayList的容量會隨著我們的需要自動按照一定規(guī)律 //進行填充,當我們確定不再添加元素時,我們要釋放多余的空間 //這就用到了Capacity屬性和TrimtoSize()方法 //利用Capacity屬性可以查看當前集合的容量 //利用TrimtoSize()方法可以釋放多余的空間 //查看當前容量 int number = students.Capacity; //去除多余的容量 students.TrimtoSize(); } }
希望本文所述對大家的C#程序設計有所幫助。
您可能感興趣的文章:
相關文章
C#實現(xiàn)數(shù)據(jù)包加密與解密實例詳解
這篇文章主要介紹了C#實現(xiàn)數(shù)據(jù)包加密與解密的方法,是一項很實用的技能,需要的朋友可以參考下2014-07-07WinForm使用DataGridView實現(xiàn)類似Excel表格的查找替換功能
這篇文章主要介紹了WinForm使用DataGridView實現(xiàn)類似Excel表格的查找替換功能,現(xiàn)在小編通過本文給大家分享查找替換實現(xiàn)過程,需要的朋友可以參考下2021-07-07