动态数组设计原理

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

 /// <summary>
 /// ObjArray 的摘要说明。
 /// 动态数组
 /// </summary>
 /// <example>
 /// ObjectArray DynArr = new ObjectArray();
 /// DynArr.addItem(11);
 /// DynArr.addItem("12");
 /// DynArr.getItem(i);
 /// DynArr.clearAll();
 /// </example>
 public class ObjArray
 {
  //对象数组
  private object[] Items;

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

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

  /// <summary>
  /// 添加一元素
  /// </summary>
  /// <param name="item">元素</param>
  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<Length;i++)
    {
     tmpList[i] = Items[i];
    }

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

  /// <summary>
  ///  删除一个元素
  /// </summary>
  /// <param name="index">元素索引</param>
  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<index;i++)
     {
      tmpList[i] = Items[i];
     }
     for(int i=index+1;i<Length;i++)
     {
      tmpList[i-1] = Items[i];
     }

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


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

  /// <summary>
  /// 清空数组
  /// </summary>
  public void clearAll()
  {
   Items = null;
  }
 }

转载于:https://www.cnblogs.com/Sue_/articles/1648720.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值