首页 / 世界杯冠军榜排名

C#中字节数组(byte[])末尾继续添加字节的示例

2025-09-20 20:49:30世界杯冠军榜排名 3566

方法一:使用List

使用List可以很容易地在末尾添加字节,然后如果需要,可以将其转换回byte[]。

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Linq;

using System.Text;

using System.Windows.Forms;

using System.Threading;

namespace WindowsFormsApplication1

{

public partial class Form1 : Form

{

public Form1()

{

InitializeComponent();

}

List byteList = new List();

private void byteAddFun()

{

byteList.Clear();

// 添加字节

byteList.Add(0x01);

byteList.Add(0x02);

byteList.Add(0x03);

// 如果需要,转换为byte[]

byte[] byteArray = byteList.ToArray();

foreach (byte b in byteArray)

textBox1.Text += b.ToString("X2") + " ";

// 添加字节

byteList.Add(0x05);

byteList.Add(0x06);

byteList.Add(0x07);

// 如果需要,转换为byte[]

byte[] byteArray2 = byteList.ToArray();

foreach (byte b in byteArray2)

textBox1.Text += b.ToString("X2") + " ";

}

private void byteAddFun2()

{

byteList.Clear();

// 添加字节

byteList.Add(0x05);

byteList.Add(0x06);

byteList.Add(0x07);

// 如果需要,转换为byte[]

byte[] byteArray2 = byteList.ToArray();

foreach (byte b in byteArray2)

textBox1.Text += b.ToString("X2") + " ";

}

private void button1_Click(object sender, EventArgs e)

{

textBox1.Text = null;

byteAddFun();

}

private void button2_Click(object sender, EventArgs e)

{

textBox1.Text = null;

byteAddFun2();

}

}

}

方法二:使用Array.Resize或新的Array.Copy

如果已经有一个byte[]并希望添加更多字节,则可以使用Array.Resize来重新调整数组的大小,但请注意这可能会导致性能问题,因为每次添加字节时都需要重新分配整个数组。

或者也可以创建一个新的更大的数组,然后使用Array.Copy将旧数组的内容复制到新数组中,并在新数组的末尾添加新的字节。

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Linq;

using System.Text;

using System.Windows.Forms;

using System.Threading;

namespace WindowsFormsApplication1

{

public partial class Form1 : Form

{

public Form1()

{

InitializeComponent();

}

private void byteAddFun()

{

byte[] byteArray = new byte[] { 0x01, 0x02, 0x03 };

// 假设我们要添加一个新的字节 0x04

byte newByte = 0x04;

// 创建一个新的更大的数组

byte[] newByteArray = new byte[byteArray.Length + 1];

// 复制旧数组的内容到新数组

Array.Copy(byteArray, 0, newByteArray, 0, byteArray.Length);

// 在新数组的末尾添加新的字节

newByteArray[newByteArray.Length - 1] = newByte;

// 现在 newByteArray 包含 [0x01, 0x02, 0x03, 0x04]

foreach (byte b in newByteArray)

textBox1.Text += b.ToString("X2") + " ";

}

private void button1_Click(object sender, EventArgs e)

{

textBox1.Text = null;

byteAddFun();

}

private void button2_Click(object sender, EventArgs e)

{

textBox1.Text = null;

byteAddFun();

}

}

}

三、注意

如果需要频繁地向数组添加字节,并且事先不知道最终的大小,那么使用List通常是一个更好的选择,因为它可以自动处理重新分配的问题,并且通常具有更好的性能。但是,如果已经知道最终的大小,或者只是偶尔需要添加字节,那么使用Array.Resize或Array.Copy可能是可以接受的。