作者rahim (forget it)
看板C_Sharp
标题Re: [问题] 如何用C#写一个动态阵列?
时间Fri Mar 23 22:42:08 2007
※ 引述《rahim (forget it)》之铭言:
: ※ 引述《GreatShot (我要拿Ph.D.!!!)》之铭言:
: : 抱歉这里我笔误 应该是arr.Count
: : 是的 每个ArrayList的元素是"各自"指向一个全新的ArrayList
: : 没那麽美好..XD
: : ArrayList有时很方便有时也很麻烦
: : 因为ArrayList里头不管你放什麽东西都会被转成object
: : 所以你要取用时得先cast一下
: : 会变成 ((ArrayList)arr[i])[j]
: : 所以我建议你去研究一下System.Collections.Generic里头的类别
: : 这是.NET 2.0才有的东西
: : 效率比ArrayList高很多
: System.Collections.Generic里面的类别
: 跟ArrayList比较接近的 是List泛型类别吗?
: http://msdn2.microsoft.com/zh-tw/library/6sh2ey19(VS.80).aspx
如果想要依照使用者输入的要求
建立一个m X n的动态阵列
那下面这样写可以吗?
Console.WriteLine("Please input the row size of matrix");
int m =Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Please input the column size of matrix");
int n = Convert.ToInt32(Console.ReadLine());
List<List<double>> arr = new List<List<double>>();
for (int i = 0; i < m; i++)
{
arr[i] = new List<double>();
for (int j = 0; j < n; j++)
{
arr[i][j] = i + j;
}
}
--
※ 发信站: 批踢踢实业坊(ptt.cc)
◆ From: 140.119.144.40
1F:推 tomex:看起来ok 03/24 00:59
2F:推 tomex:不过list<>要用add()把值塞进去,未配大小时就充值不行 03/24 01:01
3F:推 rahim:所以是改成arr.Add(new List<double>()); 03/24 04:02
4F:→ rahim:下面改成arr[i].Add(i+j); 这样以後就可以用arr[i][j]了吗? 03/24 04:03
5F:→ rahim:还有想请问一下List< >中间要放的是什麽? 03/24 04:04
6F:→ rahim:为什麽我一开始用 03/24 04:05
7F:→ rahim:List<List<double>> arr=new List<List<double>>(); 03/24 04:06
8F:→ rahim:这样可以呢?(虽然是我自己想出来的,不过想听一下讲解) 03/24 04:07