Giới thiệu
Buffer.ByteLength(Array array) trả về tổng số byte chiếm dụng bởi mảng. Với primitive types: Length * sizeof(T).
Ví dụ cơ bản
byte[] b = { 5, 9, 19, 23, 29, 35, 55, 78 };
int len = Buffer.ByteLength(b); // 8 (byte[] -> 1 byte/phần tử)
Ví dụ hoàn chỉnh
using System;
class Program
{
static void Main()
{
byte[] b = { 5, 9, 19, 23, 29, 35, 55, 78 };
int len = Buffer.ByteLength(b);
for (int i = 0; i < len; i++)
Console.WriteLine(b[i]);
Console.WriteLine("Length of byte array = " + len);
}
}
Kết quả
5 9 19 23 29 35 55 78 Length of byte array = 8
ByteLength với các kiểu khác
| Kiểu mảng | sizeof(T) | ByteLength (10 phần tử) |
|---|---|---|
| byte[] | 1 | 10 |
| short[] / ushort[] | 2 | 20 |
| int[] / uint[] / float[] | 4 | 40 |
| long[] / ulong[] / double[] | 8 | 80 |
| char[] | 2 (UTF-16) | 20 |
Lưu ý
- Chỉ hoạt động với mảng primitive (có kích thước cố định).
- Ném
ArgumentExceptioncho mảng object[], string[], hoặc multi-dimensional array. - Khác với
array.Length(số phần tử), ByteLength = số byte. - Dùng cho: tính buffer size, allocate unmanaged memory, interop.
Ví dụ thực tế: Allocate unmanaged buffer
int[] data = GetData();
int byteCount = Buffer.ByteLength(data);
IntPtr ptr = Marshal.AllocHGlobal(byteCount);
try
{
Marshal.Copy(data, 0, ptr, data.Length);
// Use ptr with native API
}
finally
{
Marshal.FreeHGlobal(ptr);
}