用索引器 来操作动态数组(ArrayList)行不通 为什么?小白求助

qq_29534947 2017-09-19 09:17:14
为什么不能操作动态数组 求助啊 网上 似乎没有我看的懂得原因
using System;
using System.Collections;
namespace fourthExcerise
{
class Inset
{
private ArrayList array = new ArrayList(size);
static int size = 5;
public Inset()
{
for (int i = 0; i < size;i++)
{
array[i] =0;
}
}
public int this[int index]
{

get
{
int tmp;
if(index>=0&&index<size)
{
tmp = array[index];//cannot implictly convert type object to int an explicit conversion 这个异常
}
else
{
tmp = 0;
}
return tmp;
}
set
{
if(index>=0&&index<size)
{
array[index] = value;
}
}
}
}
}
...全文
348 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
impasse 2017-09-23
  • 打赏
  • 举报
回复
引用 5 楼 qq_29534947 的回复:
谢谢你们的回复 终于知道了 Array ArrayList<> and List<> 的作用和区别了 前面不知道有List<> 如果不知道类型的情况下 用ArrayList 出现装箱拆箱的报错 怎么解决呢?还有 int.parse 转化数字字符串 那么如果是字母字符串呢?就报错了啊!
TryParse不会报错,非int类型返回false,out值返回0
qq_29534947 2017-09-21
  • 打赏
  • 举报
回复
谢谢你们的回复 终于知道了 Array ArrayList<> and List<> 的作用和区别了 前面不知道有List<> 如果不知道类型的情况下 用ArrayList 出现装箱拆箱的报错 怎么解决呢?还有 int.parse 转化数字字符串 那么如果是字母字符串呢?就报错了啊!
impasse 2017-09-20
  • 打赏
  • 举报
回复
如果你确认ArrayList是Int类型,请强制转换 Convert.ToInt32( array[index]) 如果你不确信,请用TryParse ArrayList才不管你存什么,都直接给你返回object
  • 打赏
  • 举报
回复
ArrayList内部对象都是Ojbect,你当然读取需要个转换过程 话说你为啥不用List<int>来代替ArrayList
threenewbee 2017-09-19
  • 打赏
  • 举报
回复
用List<T>支持索引
真相重于对错 2017-09-19
  • 打赏
  • 举报
回复
arraylist[ index ]这是个Object ,而不是int 你可以把一个int 转为object 代码如下 int a; object o =a 这就是所谓的装箱 但是你不能把一个object直接转为int object o; int a a = o; 这就是拆箱 而是 object o; int a; a = (int)o; .//转换的时候还要确定o确实存储着一个int

110,534

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧