나는 그 일을 아주 잘 수행하는 Read 제네릭 함수를 가지고있다. 바이트 버퍼에서 읽고 특정 형식을 반환합니다.C# Generics
public static T Read<T>()
{
// An T[] would be a reference type, and a lot easier to work with.
T[] t = new T[1];
// Marshal.SizeOf will fail with types of unknown size. Try and see...
int s = Marshal.SizeOf(typeof(T));
if (index + s > size)
// Should throw something more specific.
throw new Exception("Error 101 Celebrity");
// Grab a handle of the array we just created, pin it to avoid the gc
// from moving it, then copy bytes from our stream into the address
// of our array.
GCHandle handle = GCHandle.Alloc(t, GCHandleType.Pinned);
Marshal.Copy(dataRead, index, handle.AddrOfPinnedObject(), s);
index += s;
// Return the first (and only) element in the array.
return t[0];
}
문제 : 쓰기 기능을 수행하는 방법은 무엇입니까?
public static T Write<T>()
{
// An T[] would be a reference type, and a lot easier to work with.
T[] t = new T[1];
// Marshal.SizeOf will fail with types of unknown size. Try and see...
int s = Marshal.SizeOf(typeof(T));
if (index + s > size)
// Should throw something more specific.
throw new Exception("Error 101 Celebrity");
// Grab a handle of the array we just created, pin it to avoid the gc
// from moving it, then copy bytes from our stream into the address
// of our array.
GCHandle handle = GCHandle.Alloc(dataWrite, GCHandleType.Pinned);
Marshal.Copy(t, index, handle.AddrOfPinnedObject(), s); // ?? Problem
index += s;
}
"t"는 byte [] 배열이어야합니다. 어떻게해야합니까?
먼저 구조체에서만 작동하며 두 번째로 BinarySerializer를 사용하지 않는 이유는 무엇입니까? –