要維數跟著增加,即我們常說的:動態數組。
使用 System.Collection.ArrayList 類或 System.Collections.Generic.List 泛型類
使用 ArrayList 類示例:
using System.Collection;
ArrayList al = new ArrayList();
while(ns.Read(bytes, 0, bytes.Length) != 0)
{
al.Add(bytes[0]);
}
使用泛型 List 類示例(.net 2.0 版本新增的):
using System.Collection.Generic;
List<byte> list = new List<byte>();
while(ns.Read(bytes, 0, bytes.Length) != 0)
{
list.AddRange(bytes)
// 或 list.Add(bytes[0]);
}
另:若從流中讀取壹個字節,使用 ReadByte() 方法比較省事,不推薦使用 Read() 方法,示例:
using System.Collection.Generic;
List<byte> list = new List<byte>();
int value = ns.ReadByte()
while(value != -1)
{
list.Add((byte)value);
value = ns.ReadByte();
}
另2:若流支持查找,則可以通過 Length 屬性判斷流的大小初始化數組,然後壹次性讀取數據,這樣性能較好,不建議壹個字節壹個字節讀取。
// 數據量較小的流,推薦此方法(壹般流的大小最好不要查過 10M 推薦)。
byte[] buffer = new byte[ns.Length];
ns.Read(buffer, 0, buffer.Lenth);
另3:通常正規的編程中,若無法判定流大小(不支持查找)或則流太大不合適壹次性讀取,往往采用固定大小緩沖數組壹塊、壹塊的讀取(譬如:壹次讀取 1024 byte),示例:
using System.Collection.Generic;
const int BufferSize = 1024; // 定義壹個緩沖區大小的常量,以便以後修改
List<byte> list = new List<byte>();
byte[] buffer = new byte[BufferSize]; // 開辟緩沖區
int len = 0;
do
{
len = ns.Read(buffer, 0, BufferSize)
if(len == BufferSize)
{
list.AddRange(buffer);
}
else
{
// 這裏說明已經讀取到流的末尾了,已沒有 BufferSize 大小了
// 壹個壹個的放入集合
for(int index = 0; index < len; index++)
list.Add(buffer[index]);
}
}
while(len != 0)