Skip to content

ZH TW CSharp Keyword delegate

Codex edited this page Oct 11, 2026 · 2 revisions

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

C#: delegate

使用手冊C# · 實用指南

宣告可呼叫的參考類型或匿名方法; delegate* 描述了不安全程式碼中的函數指標。

簡單範例 (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學習。

Clone this wiki locally