FR CSharp Keyword unmanaged generic type constraint - LIHACHTETAN/ClassicUO-Bad-Newbie-CSharp-Scripts-IDE GitHub Wiki
Українська · Русский · English · Deutsch · Français · Italiano · Español · 繁體中文 · 日本語 · 한국어
La contrainte Where T : non gérée autorise uniquement les types valeur sans références gérées dans leur composition. Il vous permet d'utiliser sizeof(T) et T* dans un contexte non sécurisé autorisé. Il s'agit d'une contrainte de type, pas d'une convention d'appel de fonction. Il n'est pas combiné avec une structure séparée ou un new().
Enregistrez cet exemple séparément dans Example.cs. Exécutez-le indépendamment des autres exemples de cette page.
Example.cs:
// PROJECT-EXAMPLE
int Size<T>() where T : unmanaged
{
unsafe { return sizeof(T); }
}
System.Console.WriteLine(Size<int>());Résultat:
4
static int ByteSize<T>() where T : unmanaged;
static void Swap<T>(T* left, T* right) where T : unmanaged;Fichier 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>Fichier 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);
}Résultat:
4
8
Fichier 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>Fichier 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;
}
}Résultat:
25,10
Source officielle : Microsoft Apprendre.