C#中動(dòng)態(tài)數(shù)組用法實(shí)例
本文實(shí)例講述了C#中動(dòng)態(tài)數(shù)組用法。分享給大家供大家參考。具體分析如下:
ArrayList是一種動(dòng)態(tài)數(shù)組,其容量可隨著我們的需要自動(dòng)進(jìn)行擴(kuò)充.
ArrayList位于System.Collections命名空間中,所以我們?cè)谑褂脮r(shí),需要導(dǎo)入此命名空間.
下面,我們還是在Student類的基礎(chǔ)上利用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);
}
}
編寫測(cè)試類,了解ArrayList的方法
using System.Collections;
public class TestStudent
{
public static void main(String args [])
{
//建立ArrayList對(duì)象
ArrayList students = new ArrayList();
//實(shí)例化幾個(gè)Student類對(duì)象
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屬性查看該集合中的元素?cái)?shù)量
int number = students.Count;
Console.WriteLine("共有元素" + number + "個(gè)");
//讀取單個(gè)元素,因?yàn)榇嫒階rrayList中的元素會(huì)變?yōu)镺bject類型,
//所以,在讀取時(shí)間,
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);
//刪除元素, 通過對(duì)象名
students.remove(jack);
//清空元素
students.Clear();
//我們知道,ArrayList的容量會(huì)隨著我們的需要自動(dòng)按照一定規(guī)律
//進(jìn)行填充,當(dāng)我們確定不再添加元素時(shí),我們要釋放多余的空間
//這就用到了Capacity屬性和TrimtoSize()方法
//利用Capacity屬性可以查看當(dāng)前集合的容量
//利用TrimtoSize()方法可以釋放多余的空間
//查看當(dāng)前容量
int number = students.Capacity;
//去除多余的容量
students.TrimtoSize();
}
}
希望本文所述對(duì)大家的C#程序設(shè)計(jì)有所幫助。
相關(guān)文章
c# in depth的泛型實(shí)現(xiàn)實(shí)例代碼
這篇文章主要介紹了c# in depth的泛型實(shí)現(xiàn)實(shí)例代碼,學(xué)C#的同學(xué)一定會(huì)用到泛型實(shí)現(xiàn)的,這里我們提供了泛型實(shí)現(xiàn)的程序代碼,大家參考使用2013-11-11
C#實(shí)現(xiàn)數(shù)據(jù)包加密與解密實(shí)例詳解
這篇文章主要介紹了C#實(shí)現(xiàn)數(shù)據(jù)包加密與解密的方法,是一項(xiàng)很實(shí)用的技能,需要的朋友可以參考下2014-07-07
WinForm使用DataGridView實(shí)現(xiàn)類似Excel表格的查找替換功能
這篇文章主要介紹了WinForm使用DataGridView實(shí)現(xiàn)類似Excel表格的查找替換功能,現(xiàn)在小編通過本文給大家分享查找替換實(shí)現(xiàn)過程,需要的朋友可以參考下2021-07-07

