0
我有一個閱讀通用函數,它的工作非常好。它從字節緩衝區讀取並返回特定類型C#泛型
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? – 2009-04-20 06:20:25