Generic BitConverter.GetBytes possible in .NET?

血红的双手。 提交于 2019-12-12 18:02:09

问题


Is it possible to create a method like BitConverter.GetBytes() that accepts as input also a parameter of type Object, without using Marshaling as done here?

Or the only solution, if a type Object is given as input, is to implement a case on all available .NET value types?


回答1:


No it isn't. The internal layout of a class or struct is undiscoverable. Marshaling is required, guided by a [StructLayout], to convert that undocumented layout to a known one. The JIT compiler readily takes advantage of this, it re-orders the fields in a struct for example to get them properly aligned and require the minimum of storage. This defeats any tricks that messes with unmanaged pointers. The simple value types behave predictably, but they are already well covered by BitConverter. Structures are your nemesis.

This is one reason why it took so long for memory-mapped files to be supported by the .NET framework. But they'll be available in .NET 4.0, you could take advantage of the MemoryMappedViewAccessor class. It still uses marshaling, it is hidden under the floor mat.




回答2:


Bitconverter.GetBytes((dynamic)v);



来源:https://stackoverflow.com/questions/2370436/generic-bitconverter-getbytes-possible-in-net

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