Overlaying several CLR reference fields with each other in explicit struct?

前端 未结 5 1659
日久生厌
日久生厌 2021-02-07 20:59

Edit: I\'m well aware of that this works very well with value types, my specific question is about using this for reference types.

Edit2:

5条回答
  •  天涯浪人
    2021-02-07 21:16

    If you align the type in an unsafe way, the runtime will throw a TypeLoadException on load even when compiling with /unsafe. So I think you are safe.

    I'm guessing--since you can use StructLayout and compile your code without /unsafe flags-- that this is a feature of the CLR. You need the StructLayout attribute simply because C# has no direct means of declaring types this way.

    Take a look at this page which details some of the way C# structs translates into IL, you'll notice that there are many memory layouts support built-in to the IL/CLR itself.

提交回复
热议问题