如何将Marshal.SizeOf(Object)替换为Marshal.SizeOf< T>()? [英] How can I replace Marshal.SizeOf(Object) with Marshal.SizeOf<T>()?
问题描述
我正在从现有代码中构建一个 Universal 类库,并且收到一些编译器警告,提示我一生都无法解决该问题.
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.
我有这样的代码:
void SomeMethod(Object data)
{
var size = Marshal.SizeOf(data);
...
}
代码已构建,但是在 Universal 项目(我猜是.NET 4.5.1和更高版本的项目)中,我收到以下编译器警告:
The code builds, but in the Universal project (and, I guess, .NET 4.5.1 and higher projects) I get the following compiler warning:
警告CS0618:"System.Runtime.InteropServices.Marshal.SizeOf(object)"已过时:"SizeOf(Object)在将来的版本中可能不可用.而是使用SizeOf< T>().
warning CS0618: 'System.Runtime.InteropServices.Marshal.SizeOf(object)' is obsolete: 'SizeOf(Object) may be unavailable in future releases. Instead, use SizeOf<T>().
但是在上述情况下,如何使用通用的无参数方法Marshal.SizeOf<T>()
为Marshal.SizeOf(Object)
创建替换?从理论上讲,我可能不知道data
是什么类型?
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?
是因为使用Marshal.SizeOf(Object)
被归为Obsolete
被认为是不好的做法吗?带回家的消息真的应该是完全重构代码"吗?
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)
:
我认为这是您需要的方法,但是由于
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>()
:
当您自己的类可能已经是泛型类并且您具有T
但没有所使用的泛型类型的实际实例时,此方法会派上用场.在这种情况下,应选择此方法.
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;
}
这篇关于如何将Marshal.SizeOf(Object)替换为Marshal.SizeOf< T>()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!