How can I replace Marshal.SizeOf(Object) with Marshal.SizeOf<T>()?

徘徊边缘 提交于 2019-12-05 08:12:10

Okay, after getting your comments it seems that everything you need is already there:

SizeOf<T>(T): I think this is the method you need, but you don't have to define the generic parameter explictly, due to type inference. You simple write var size = Marshal.SizeOf(myStructure); and the compiler will extract the type from the given object and fill out the generic parameter.

SizeOf<T>(): This method comes in handy when your own class is maybe already a generic class and you have a T but no real instance of the used generic type. In that case this method should be choosen.

How about this reflection approach:

private static int MySizeOf(object structure)
{
    var marshalType = typeof(Marshal);
    var genericSizeOfMethod = marshalType.GetMethod("SizeOf", Type.EmptyTypes);
    var sizeOfMethod = genericSizeOfMethod.MakeGenericMethod(structure.GetType());
    var size = (int)sizeOfMethod.Invoke(null, null);

    return size;
}

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!