一般的な構造体のサイズを調べる必要があります (sizeof(T) のようにできないか、Marshal.SizeOf(...) 0> を使用するとエラーが発生します)
だから私は書いた:
public static class HelperMethods
{
static HelperMethods()
{
SizeOfType = createSizeOfFunc();
}
public static int SizeOf<T>()
{
return SizeOfType(typeof(T));
}
public static readonly Func<Type, int> SizeOfType = null;
private static Func<Type, int> createSizeOfFunc()
{
var dm = new DynamicMethod("SizeOfType", typeof(int), new Type[] { typeof(Type) });
ILGenerator il = dm.GetILGenerator();
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Sizeof); //needs to be il.Emit(OpCodes.Sizeof, typeof(something))
il.Emit(OpCodes.Ret);
var func = (Func<Type, int>)dm.CreateDelegate(typeof(Func<Type, int>));
return func;
}
}
問題は、il.Emit(OpCodes.Sizeof) がメソッド (SizeOfType) の作成中に渡すことができない引数を必要とすることです。IL を使用して、スタックにあるパラメーターを il.Emit(OpCodes.Sizeof) に渡すにはどうすればよいですか? (または別の解決策ですが、2番目の回答で提案されている結果ではなく、関数(デリゲート)をキャッシュしたい)