Byte类型怎么增量赋值??

2025-03-26 01:19:37
推荐回答(1个)
回答1:

要拷贝数组用 System.Array.Copy 静态方法,但要确保目标数组有足够的大小容纳源数组。

要维数跟着增加,即我们常说的:动态数组。
使用 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 list = new List();
while(ns.Read(bytes, 0, bytes.Length) != 0)
{
list.AddRange(bytes)
// 或 list.Add(bytes[0]);
}

另:若从流中读取一个字节,使用 ReadByte() 方法比较省事,不推荐使用 Read() 方法,示例:
using System.Collection.Generic;
List list = new List();
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 list = new List();
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)