且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在C#中,是否可以在不创建新数组的情况下将字节数组转换为其他类型?

更新时间:2023-09-16 15:46:58

有可能吗?实际上,是的!

Is it possible? Practically, yes!

自.NET Core 2.1起,MemoryMarshal允许我们针对跨度执行此操作.如果您对跨度而不是数组感到满意,那么可以.

Since .NET Core 2.1, MemoryMarshal lets us do this for spans. If you are satisfied with a span instead of an array, then yes.

var intSpan = MemoryMarshal.Cast<byte, int>(myByteArray.AsSpan());

int跨度将包含byteCount/4个整数.

The int span will contain byteCount / 4 integers.

关于自定义结构...该文档声称转换的两面都需要原始类型".但是,您可以尝试使用ref struct并看到这是 actual 约束.如果它奏效,我不会感到惊讶!

As for custom structs... The documentation claims to require a "primitive type" on both sides of the conversion. However, you might try using a ref struct and see that is the actual constraint. I wouldn't be surprised if it worked!

请注意,引用结构仍然非常受限制,但是这种限制对于我们正在谈论的重新解释类型转换是有意义的.

Note that ref structs are still very limiting, but the limitation makes sense for the kind of reinterpret casts that we are talking about.

哇,约束要严格得多.它需要任何结构,而不是基元.它甚至不必是ref struct.如果您的结构在其层次结构中的任意位置包含引用类型,则只会抛出 runtime 检查.那讲得通.因此,这应该适用于您的自定义结构以及适用于int的结构.享受吧!

Wow, the constraint is much less strict. It requires any struct, rather than a primitive. It does not even have to be a ref struct. There is only a runtime check that will throw if your struct contains a reference type anywhere in its hierarchy. That makes sense. So this should work for your custom structs as well as it does for ints. Enjoy!