如果類型為下列任何類型,則為 Unmanaged 類型 :
-
sbyte、byte、short、ushort、、、intuintlongulongnintnuintcharfloatdouble、、 或decimalbool - 任何 列舉 類型
- 任何 指標 類型
- 成員都是 Unmanaged 型別的 Tuple
- 任何只包含 Unmanaged 型別欄位的使用者定義 結構 類型。
您可以使用 unmanaged 條件約束 來指定類型參數是非指標、不可為 Null 的 Unmanaged 類型。
只包含 Unmanaged 型別字段的 建構 結構類型也是 Unmanaged,如下列範例所示:
using System;
public struct Coords<T>
{
public T X;
public T Y;
}
public class UnmanagedTypes
{
public static void Main()
{
DisplaySize<Coords<int>>();
DisplaySize<Coords<double>>();
}
private unsafe static void DisplaySize<T>() where T : unmanaged
{
Console.WriteLine($"{typeof(T)} is unmanaged and its size is {sizeof(T)} bytes");
}
}
// Output:
// Coords`1[System.Int32] is unmanaged and its size is 8 bytes
// Coords`1[System.Double] is unmanaged and its size is 16 bytes
泛型結構可能是 Unmanaged 和 Managed 建構型別的來源。 上述範例會定義泛型結構 Coords<T> ,並呈現 Unmanaged 建構類型的範例。 Managed 類型的範例為 Coords<object>。 它是受控的,因為它具有型別的 object 欄位,這是受控的。 如果您希望 所有 建構的類型都是 Unmanaged 類型,請使用 unmanaged 泛型結構定義中的條件約束:
public struct Coords<T> where T : unmanaged
{
public T X;
public T Y;
}