私はその仕事を非常にうまく処理する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 []配列である必要があります。私はそれをどのように達成するのですか?
まず、これは構造体でのみ機能し、2番目の理由はBinarySerializerを使用するだけではありませんか? –