ภาพรวม
คลาส Buffer ใน namespace System ให้เมธอดสำหรับจัดการ ช่วงไบต์ (byte ranges) ในอาร์เรย์ primitive types โดยตรงระดับหน่วยความจำ
เมธอดหลัก
BlockCopy(src, srcOffset, dst, dstOffset, count)- คัดลอกไบต์ByteLength(array)- ขนาดรวมเป็นไบต์GetByte(array, index)- อ่านไบต์SetByte(array, index, value)- เขียนไบต์
ตัวอย่างโค้ดเต็ม
using System;
class Demo
{
static void Main()
{
byte[] b1 = new byte[] { 39, 45, 58 };
byte[] b2 = new byte[5];
Buffer.BlockCopy(b1, 0, b2, 0, 3);
BufferFunc(b2);
}
static void BufferFunc(byte[] a)
{
for (int j = 0; j < a.Length; j++) Console.Write(a[j]);
Console.WriteLine();
}
}
ผลลัพธ์
39455800
เมื่อไหร่ควรใช้ Buffer
- การจัดการข้อมูล binary ระดับต่ำ (low-level)
- Interop กับ unmanaged code / C++ / Win32 API
- Serialization / deserialization แบบ custom
- Image/audio processing ต้องการความเร็วสูงสุด
- ไม่ควรใช้ สำหรับ business logic ปกติ - ใช้ LINQ, List, Array methods แทน