非托管类型(C# 参考)Unmanaged types (C# reference)

如果某个类型是以下类型之一,则它是非托管类型 :A type is an unmanaged type if it's any of the following types:

  • sbytebyteshortushortintuintlongulongcharfloatdoubledecimalboolsbyte, byte, short, ushort, int, uint, long, ulong, char, float, double, decimal, or bool
  • 任何枚举类型Any enum type
  • 任何指针类型Any pointer type
  • 任何用户定义的 struct 类型,只包含非托管类型的字段,并且在 C# 7.3 及更早版本中,不是构造类型(包含至少一个类型参数的类型)Any user-defined struct type that contains fields of unmanaged types only and, in C# 7.3 and earlier, is not a constructed type (a type that includes at least one type argument)

从 C# 7.3 开始,可使用 unmanaged 约束指定:类型参数为“非指针、不可为 null 的非托管类型”。Beginning with C# 7.3, you can use the unmanaged constraint to specify that a type parameter is a non-pointer, non-nullable unmanaged type.

从 C# 8.0 开始,仅包含非托管类型的字段的 构造 结构类型也是非托管类型,如以下示例所示:Beginning with C# 8.0, a constructed struct type that contains fields of unmanaged types only is also unmanaged, as the following example shows:

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

泛型结构可以是非托管类型的源,也可以是不是非托管构造类型的源。A generic struct may be the source of both unmanaged and not unmanaged constructed types. 前面的示例定义一个泛型结构 Coords<T>,并提供非托管构造类型的示例。The preceding example defines a generic struct Coords<T> and presents the examples of unmanaged constructed types. 不是非托管类型情况的示例是 Coords<object>The example of not an unmanaged type is Coords<object>. 它不是非托管性质,因为它具有不是非托管性质的 object 类型的字段。It's not unmanaged because it has the fields of the object type, which is not unmanaged. 如果你希望所有 构造类型都是非托管类型,请在泛型结构的定义中使用 unmanaged 约束:If you want all constructed types to be unmanaged types, use the unmanaged constraint in the definition of a generic struct:

public struct Coords<T> where T : unmanaged
{
    public T X;
    public T Y;
}

C# 语言规范C# language specification

有关详细信息,请参阅 C# 语言规范指针类型部分。For more information, see the Pointer types section of the C# language specification.

请参阅See also