可能一般BitConverter.GetBytes在.NET?BitConverter、GetBytes、NET

2023-09-08 08:32:25 作者:做自己就好

是否有可能创建例如 BitConverter.GetBytes的方法()接受输入也键入对象的参数,不使用编组为已完成这里?

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?

或者是唯一的解决办法,如果一个Object类型作为输入,是实施情况上所有可用的.NET 值类型

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

推荐答案

没有事实并非如此。一类或结构的内部布局是不可发现。封送处理是必需的,由[StructLayout]为导向,以无证布局转换为已知的。 JIT编译器很容易地利用了这一点,它重新排序的结构例如域,让他们正确对齐,并要求最小的存储。这违背了与非托管指针弄乱任何技巧。简单的值类型的行为predictably,但他们早已覆盖BitConverter。结构是你的克星。

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.

这就是为什么花了这么长的时间内存映射文件由.NET框架的支持。但他们将在.NET 4.0中可用,您可以采取MemoryMappedViewAccessor类的优势。它仍然采用封送处理,它在地板垫隐藏的。

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.