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

泄露秘密 提交于 2019-12-07 04:40:50

问题


I am building a Universal class library from existing code, and I get some compiler warnings that I for the life of it cannot figure out what to do with.

I have code like this:

void SomeMethod(Object data)
{
  var size = Marshal.SizeOf(data);
  ...
}

The code builds, but in the Universal project (and, I guess, .NET 4.5.1 and higher projects) I get the following compiler warning:

warning CS0618: 'System.Runtime.InteropServices.Marshal.SizeOf(object)' is obsolete: 'SizeOf(Object) may be unavailable in future releases. Instead, use SizeOf<T>().

But how do I create a replacement for Marshal.SizeOf(Object) in the above case using the generic parameter-less method Marshal.SizeOf<T>()? Theoretically, I might not have any idea what type data is?

Is it because using Marshal.SizeOf(Object) is considered bad practice that it has been attributed Obsolete? And the take-home message should really be "refactor the code completely"?


回答1:


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;
}



来源:https://stackoverflow.com/questions/26555605/how-can-i-replace-marshal-sizeofobject-with-marshal-sizeoft

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