您的位置:首页 > 其它

StructLayout在继承关系中的使用

2008-01-16 11:17 369 查看
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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: