Chinaunix首页 | 论坛 | 博客
  • 博客访问: 581760
  • 博文数量: 208
  • 博客积分: 3286
  • 博客等级: 中校
  • 技术积分: 1780
  • 用 户 组: 普通用户
  • 注册时间: 2007-09-24 20:38
文章分类

全部博文(208)

文章存档

2012年(7)

2011年(28)

2010年(21)

2009年(76)

2008年(65)

2007年(11)

我的朋友

分类: C/C++

2007-11-27 15:46:40

 C#中所有数据类型都来自Object类,所以数组可以存储不同的类型,但是数组对象一旦创建,长度就不可改变,在实际应用中存在不方便之处。下面例程介绍了一种开发动态数组的方法。

 ///


 /// ObjArray 的摘要说明。
 /// 动态数组
 ///

 ///
 /// ObjectArray DynArr = new ObjectArray();
 /// DynArr.addItem(11);
 /// DynArr.addItem("12");
 /// DynArr.getItem(i);
 /// DynArr.clearAll();
 ///

 public class ObjArray
 {
  //对象数组
  private object[] Items;

  //对象数组的长度
  public int Length
  {
   get
   {
    if(Items == null)
     return 0;
    else
     return Items.Length;
   }
  }

  ///


  /// 构造函数
  ///

  public ObjArray()
  {
   //
   // TODO: 在此处添加构造函数逻辑
   //
   Items = null;
  }

  ///


  /// 添加一元素
  ///

  /// 元素
  public void addItem(object item)
  {
   if(Items == null)
   {
    Items = new object[1];
    Items[0] = item;
    return;
   }
   else
   {
    object[] tmpList = new object[Length+1];
    for(int i=0;i    {
     tmpList[i] = Items[i];
    }

    tmpList[Length] = item;
    Items = tmpList;
    return;
   }
  }

  ///


  ///  删除一个元素
  ///

  /// 元素索引
  public void deleteItem(int index)
  {
   if(Items == null)
    return;
   else
   {
    //如果索引没有越界
    if(index >=0 && index < Length && Length>1)
    {
     object[] tmpList = new object[Length-1];
     for(int i=0;i     {
      tmpList[i] = Items[i];
     }
     for(int i=index+1;i     {
      tmpList[i-1] = Items[i];
     }

     Items = tmpList;
     return;
    }
    else
    {
     if(index == 0 && Length<=1)
     {
      Items = null;
      return;
     }
     else
      return;
    }
   }
  }


  ///


  /// 读取元素
  ///

  /// 元素索引
  /// 一个元素
  public object getItem(int index)
  {
   if(Items == null)
    return null;
   else
   {
    if(index >= 0 && index < Length)
     return Items[index];
    else
     return null;
   }
  }

  ///


  /// 清空数组
  ///

  public void clearAll()
  {
   Items = null;
  }
 }

阅读(1316) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~