LayoutKind 列舉

定義

控制匯出至 Unmanaged 程式碼時的物件配置。

C#
public enum LayoutKind
C#
[System.Serializable]
public enum LayoutKind
C#
[System.Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
public enum LayoutKind
繼承
LayoutKind
屬性

欄位

名稱 Description
Auto 3

執行階段會自動選擇 Unmanaged 記憶體中物件成員的適當配置。 使用這個列舉成員定義的物件不可以在 Managed 程式碼以外公開。 嘗試這麼做會產生例外狀況。

Explicit 2

Unmanaged 記憶體中每個物件成員的精確位置是被明確地控制(受制於Pack欄位的設定)。 每個成員必須使用 FieldOffsetAttribute,表示該欄位在型別中的位置。

Sequential 0

物件的成員是依序配置的,其順序即是將它們匯出至 Unmanaged 記憶體時所出現的順序。 成員是根據 Pack 中所指定的封裝來配置。

範例

下列範例顯示函式的 PtInRect Managed 宣告,它會檢查某個點是否位於矩形內,並定義 Point 具有循序配置的結構,以及 Rect 具有明確配置的結構。

C#
enum Bool
{
   False = 0,
   True
};
[StructLayout(LayoutKind.Sequential)]
public struct Point
{
   public int x;
   public int y;
}

[StructLayout(LayoutKind.Explicit)]
public struct Rect
{
   [FieldOffset(0)] public int left;
   [FieldOffset(4)] public int top;
   [FieldOffset(8)] public int right;
   [FieldOffset(12)] public int bottom;
}

internal static class NativeMethods
{
   [DllImport("user32.dll", CallingConvention=CallingConvention.StdCall)]
   internal static extern Bool PtInRect(ref Rect r, Point p);
};

class TestApplication
{
   public static void Main()
   {
      try
      {
         Bool bPointInRect = 0;
         Rect myRect = new Rect();
         myRect.left = 10;
         myRect.right = 100;
         myRect.top = 10;
         myRect.bottom = 100;
         Point myPoint = new Point();
         myPoint.x = 50;
         myPoint.y = 50;
         bPointInRect = NativeMethods.PtInRect(ref myRect, myPoint);
         if(bPointInRect == Bool.True)
            Console.WriteLine("Point lies within the Rect");
         else
            Console.WriteLine("Point did not lie within the Rect");
      }
      catch(Exception e)
      {
         Console.WriteLine("Exception : " + e.Message);
      }
   }
}

備註

這個列舉會搭配 使用 StructLayoutAttribute。 Common Language Runtime 預設會使用 Auto 版面配置值。 若要減少與 Auto 值相關聯的配置相關問題,C#、Visual Basic 和 C++ 編譯程式會指定 Sequential 實值類型的配置。

重要

欄位 StructLayoutAttribute.Pack 會控制數據欄位的對齊方式,因此不論您指定的值為何 LayoutKind ,都會影響版面配置。 根據預設,值為 Pack 0,表示目前平臺的預設封裝大小。 例如,當您使用 Explicit 版面配置值並在位元組界限上指定欄位對齊時,您必須設定 Pack 為 1 以取得所需的結果。

適用於

產品 版本
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 2.0, 2.1
UWP 10.0