我有一个字节数组,我只需要读取前3个字节而不是更多。
C# 4.0
这些中的任何一个都足够吗?
IEnumerable<byte> firstThree = myArray.Take(3);
byte[] firstThreeAsArray = myArray.Take(3).ToArray();
List<byte> firstThreeAsList = myArray.Take(3).ToList();
byte[] firstThreeAsArraySlice = myArray[..3];
Byte byte1 = bytesInput[0];
Byte byte2 = bytesInput[1];
Byte byte3 = bytesInput[2];
或者在数组中:
Byte[] threeBytes = new Byte[] { bytesInput[0], bytesInput[1], bytesInput[2] };
或者:
Byte[] threeBytes = new Byte[3];
Array.Copy(bytesInput, threeBytes, 0, 3);
// not sure on the overload but its similar to this
简单的for循环也可以完成这项工作。
for(int i = 0; i < 3; i++)
{
// your logic
}
或者直接在数组中使用索引。
byte first = byteArr[0];
byte second = byteArr[1];
byte third = byteArr[2];
byte b1 = bytearray[0];
byte b2 = bytearray[1];
byte b3 = bytearray[2];
数组的索引从0开始,因此你的数组中第一个3个字节分别在0、1和2的位置上。