Skip to content

RU CSharp Keyword delegate

Codex edited this page Oct 11, 2026 · 2 revisions

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

C#: delegate

Справочник C# · Практическое руководство

Объявляет тип callable-ссылки или анонимный метод; delegate* описывает function pointer в unsafe-коде.

Простой пример (Example.cs)

Сохраните этот пример отдельно как Example.cs. Запускайте его независимо от остальных примеров страницы.

Example.cs:

// PROJECT-EXAMPLE
Twice twice = value => value * 2;
System.Console.WriteLine(twice(4));
delegate int Twice(int value);

Результат:

8

Синтаксис

delegate ReturnType Name(...); / delegate(...) { ... } / delegate*<...>

Приклад 1: базова форма

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.IO;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;

public static class Program
{
    public static async Task Main(string[] args)
    {
        Transform change = value => value * 2;
        Console.WriteLine(change(4));
    }
}
public delegate int Transform(int value);

Пример 2: другая практическая форма

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.IO;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;

public static class Program
{
    public static async Task Main(string[] args)
    {
        Func<int, int> square = delegate(int value) { return value * value; };
        Action<string> report = text => Console.WriteLine(text);
        report(square(3).ToString());
    }
}

Приклад 3

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.IO;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;

public static class Program
{
    public static async Task Main(string[] args)
    {
        Change increment = (ref value) => value++;
        int number = 4; increment(ref number);
        Console.WriteLine(number);
    }
}
public delegate void Change(ref int value);

Официальный источник: Microsoft Learn.

Clone this wiki locally