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

前端 未结 5 1667
日久生厌
日久生厌 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:10

    I can't see how the explicit-layout version can be verifiable without the runtime injecting extra checks anyway, since it allows you to see a non-null reference to something that isn't of the declared type.

    This would be safer:

    struct Overlaid { // could also be a class for reference-type semantics
        private object asObject;
        public object AsObject {get {return asObject;} set {asObject = value;} }
        public Foo AsFoo { get {return asObject as Foo;} set {asObject = value;} }
        public Bar AsBar { get {return asObject as Bar;} set {asObject = value;} }
    }
    

    No risk of torn references etc, and still only a single field. It doesn't involve any risky code, etc. In particular, it doesn't risk something silly like:

        [FieldOffset(0)]
        public object AsObject;
        [FieldOffset(0)]
        public Foo AsFoo;
        [FieldOffset(1)]
        public Bar AsBar; // kaboom!!!!
    

    Another issue is that you can only support a single field this way unless you can guarantee the CPU mode; offset 0 is easy, but it gets trickier if you need multiple fields and need to support x86 and x64.

提交回复
热议问题