StructLayout在继承关系中的使用

Type Layout in Inheritance chains
A type has a type layout attribute, which specifies how the fields of an instance of a type are arranged. A type can have only one layout attribute.
There are 3 possible kinds of layout:
 
Auto – the layout is done by the CLI. This is the layout that ILASM uses if no layout attribute is specified by the user.
 
Explicit – the layout of the fields is explicitly provided. Note, that generic types cannot have explicit layout.
 
[ StructLayout( LayoutKind.Explicit )]
public class C
{
 [ FieldOffset(0)] public int i;
 [ FieldOffset(4)] public object o;
}
 
Sequential – The fields are laid out sequentially as they appear in the definition of the type.
 
[StructLayout( LayoutKind.Sequential, Pack = 1)]
public struct S2
{
            public int i1;
            public char c1;
}
 
One of the questions I have seen asked with regard to layout is why in some cases using LayoutKind.Sequential or LayoutKind.Explicit causes a TypeLoadException to be thrown when the type is used.
The reason is that layout cannot start part way down the inheritance chain.
If a type is marked Sequential or Explicit, then it has layout. If the type is part of an inheritance chain, then all its parent classes must have layout as well, up to the type that directly extends System.Object or System.ValueType.
If somewhere along the inheritance chain a parent type has no layout, runtime will throw a TypeLoadException.
However, it is valid to stop using layout at any point down the chain.
 
Examples from ECMA spec:
In the diagrams below, Class A derives from System.Object; Class B derives from A; class C derives from B. System.Object has no layout. But A, B, and C are all defined with layout, and that is valid.
The situation with classes E, F, and G is similar - G has no layout, and this too is valid.
In the following two cases the inheritance chain is invalid. On the left, H doesn't have a layout and on the right there is a 'hole' in the inheritance chain, at L.
Published Tuesday, May 16, 2006 2:24 AM by dmilirud
 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值