Skip to content

FR CSharp Keyword managed function pointer calling convention

Codex edited this page Oct 11, 2026 · 2 revisions

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

C# : managed — convention d'appel du pointeur de fonction

Manuel C# · Guide pratique

Managed dans le type délégué* spécifie un accord d'appel géré ; c'est également l'option par défaut. L'adresse est obtenue par l'opérateur & à partir de la méthode statique. Les déclarations et les appels de pointeurs sont exécutés dans un contexte non sécurisé ; le projet doit autoriser des blocs dangereux. Un pointeur de fonction n’est pas un objet délégué.

Exemple simple (Example.cs)

Enregistrez cet exemple séparément dans Example.cs. Exécutez-le indépendamment des autres exemples de cette page.

Example.cs:

// PROJECT-EXAMPLE
unsafe
{
    delegate* managed<int, int> twice = &Twice;
    System.Console.WriteLine(twice(4));
}
static int Twice(int value) => value * 2;

Activez <AllowUnsafeBlocks>true</AllowUnsafeBlocks> dans le projet. Le pointeur est valide uniquement dans la portée indiquée.

Résultat:

8

Syntaxe

delegate* managed<int, int> operation = &Transform;

L'adresse de la méthode statique de calcul du carré

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()
    {
        delegate* managed<int, int> square = &Square;
        Console.WriteLine(square(7));
    }
    private static int Square(int value) => value * value;
}

Résultat:

49

Passer l'opération sélectionnée à une autre méthode

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()
    {
        delegate* managed<int, int, int> combine = &Add;
        Console.WriteLine(Apply(combine, 8, 3));
        combine = &Subtract;
        Console.WriteLine(Apply(combine, 8, 3));
    }
    private static int Apply(delegate* managed<int, int, int> operation, int left, int right)
        => operation(left, right);
    private static int Add(int left, int right) => left + right;
    private static int Subtract(int left, int right) => left - right;
}

Résultat:

11
5

Source officielle : Microsoft Apprendre.

Clone this wiki locally