类型是 非托管类型 (如果类型为以下任一类型):
-
sbyte
、byte
、、ushort
short
、int
、uint
double
long
char
ulong
nint
nuint
float
或decimal
bool
- 任何 枚举 类型
- 任何 指针 类型
- 一个 元组 ,其成员都是非托管类型
- 任何仅包含非托管类型的字段的用户定义 结构 类型。
可以使用 unmanaged
约束 指定类型参数是非指针、不可为 null 的非托管类型。
包含非托管类型的字段的 构造 结构类型也是非托管的,如以下示例所示:
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
泛型结构可以是非托管类型和托管构造类型的源。 前面的示例定义泛型结构 Coords<T>
,并演示非托管构造类型的示例。 托管类型的示例为 Coords<object>
. 它是托管的,因为它具有类型(托管)的 object
字段。 如果希望 所有 构造类型都是非托管类型,请使用 unmanaged
泛型结构定义中的约束:
public struct Coords<T> where T : unmanaged
{
public T X;
public T Y;
}