当前位置: 移动技术网 > IT编程>开发语言>c# > C#中动态数组用法实例

C#中动态数组用法实例

2019年07月18日  | 移动技术网IT编程  | 我要评论
本文实例讲述了c#中动态数组用法。分享给大家供大家参考。具体分析如下: arraylist是一种动态数组,其容量可随着我们的需要自动进行扩充. arraylist位于s

本文实例讲述了c#中动态数组用法。分享给大家供大家参考。具体分析如下:

arraylist是一种动态数组,其容量可随着我们的需要自动进行扩充.

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属性查看该集合中的元素数量
   int number = students.count; 
    console.writeline("共有元素" + number + "个"); 
   //读取单个元素,因为存入arraylist中的元素会变为object类型,
   //所以,在读取时间, 
   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循环 
   foreach(object o in students) 
   { 
     student b = o as student; 
     b.say(); 
   } 
   //删除元素 通过索引删除 
   students.removeat(0); 
   //删除元素,  通过对象名 
   students.remove(jack); 
   //清空元素 
   students.clear(); 
   //我们知道,arraylist的容量会随着我们的需要自动按照一定规律
   //进行填充,当我们确定不再添加元素时,我们要释放多余的空间
   //这就用到了capacity属性和trimtosize()方法 
   //利用capacity属性可以查看当前集合的容量   
   //利用trimtosize()方法可以释放多余的空间 

   //查看当前容量 
   int number = students.capacity;
   //去除多余的容量
   students.trimtosize();
   } 
}

希望本文所述对大家的c#程序设计有所帮助。

如您对本文有疑问或者有任何想说的,请 点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网