Skip to content

DE 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 – Funktionszeiger-Aufrufkonvention

Handbuch C# · Praktischer Leitfaden

„Managed im Delegate*-Typ“ gibt eine verwaltete Anrufvereinbarung an. Dies ist auch die Standardoption. Die Adresse wird durch den &-Operator aus der statischen Methode ermittelt. Zeigerdeklarationen und -aufrufe werden in einem unsicheren Kontext ausgeführt; Das Projekt muss unsichere Blöcke zulassen. Ein Funktionszeiger ist kein Delegate-Objekt.

Einfaches Beispiel (Example.cs)

Speichern Sie dieses Beispiel separat als Example.cs. Führen Sie es unabhängig von den anderen Beispielen dieser Seite aus.

Example.cs:

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

Aktivieren Sie <AllowUnsafeBlocks>true</AllowUnsafeBlocks> im Projekt. Der Zeiger ist nur im gezeigten Bereich gültig.

Ergebnis:

8

Syntax

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

Die Adresse der statischen Methode zur Berechnung des Quadrats

Datei 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>

Datei 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;
}

Ergebnis:

49

Übergabe der ausgewählten Operation an eine andere Methode

Datei 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>

Datei 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;
}

Ergebnis:

11
5

Offizielle Quelle: Microsoft Learn.

Clone this wiki locally