Skip to content

ES CSharp Keyword unmanaged generic type constraint

Codex edited this page Oct 11, 2026 · 2 revisions

Українська · Русский · English · Deutsch · Français · Italiano · Español · 繁體中文 · 日本語 · 한국어

C#: unmanaged — límite de parámetro de tipo

Manual C# · Guía Práctica

La restricción donde T: no administrada solo permite tipos de valores sin referencias administradas en su composición. Le permite usar sizeof(T) y T* en un contexto inseguro permitido. Esta es una restricción de tipo, no una convención de llamada a función. No se combina con estructuras separadas o nuevas ().

Ejemplo sencillo (Example.cs)

Guarde este ejemplo por separado como Example.cs. Ejecútelo independientemente de los demás ejemplos de esta página.

Example.cs:

// PROJECT-EXAMPLE
int Size<T>() where T : unmanaged
{
    unsafe { return sizeof(T); }
}
System.Console.WriteLine(Size<int>());

Resultado:

4

Sintaxis

static int ByteSize<T>() where T : unmanaged;
static void Swap<T>(T* left, T* right) where T : unmanaged;

El tamaño de un tipo simple y estructura sin referencias.

Archivo Example.csproj:

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net10.0</TargetFramework>
    <LangVersion>14.0</LangVersion>
    <Nullable>enable</Nullable>
    <AllowUnsafeBlocks>true</AllowUnsafeBlocks>
  </PropertyGroup>

</Project>

Archivo Program.cs:

using System;

public struct GridPoint { public int X; public int Y; }
internal static unsafe class Program
{
    public static void Main()
    {
        Console.WriteLine(ByteSize<int>());
        Console.WriteLine(ByteSize<GridPoint>());
    }
    private static int ByteSize<T>() where T : unmanaged => sizeof(T);
}

Resultado:

4
8

Intercambio generalizado de valores mediante punteros

Archivo Example.csproj:

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net10.0</TargetFramework>
    <LangVersion>14.0</LangVersion>
    <Nullable>enable</Nullable>
    <AllowUnsafeBlocks>true</AllowUnsafeBlocks>
  </PropertyGroup>

</Project>

Archivo Program.cs:

using System;

internal static unsafe class Program
{
    public static void Main()
    {
        int left = 10;
        int right = 25;
        Swap(&left, &right);
        Console.WriteLine($"{left},{right}");
    }
    private static void Swap<T>(T* left, T* right) where T : unmanaged
    {
        T temporary = *left;
        *left = *right;
        *right = temporary;
    }
}

Resultado:

25,10

Fuente oficial: Microsoft Aprender.

Clone this wiki locally