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"?
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