C#•ラムダとデリゲート
C# のラムダ式とデリゲート(Action、Func)
C# のデリゲート型(戻り値なしの Action<T> と値を返す Func<T, TResult>)を学びます。
構文
Func<int, int, int> add = (a, b) => a + b;
Action<string> print = s => Console.WriteLine(s);
パラメータと値
この構文の主な構成要素と指定可能な値:
| パラメータ | 型 | 説明 |
|---|---|---|
| Func<T, TResult> | Delegate | 値を返すメソッドをカプセル化します。 |
| Action<T> | Delegate | void を返すメソッドをカプセル化します。 |
そのまま実行できるコード例
Compilra で実行可能C# をローカルにインストールせずに、この動作する完全なコード例を直接実行できます:
using System;
public class Program {
public static void Main() {
// 1. Func delegate returning double
Func<double, double, double> computeArea = (width, height) => width * height;
Console.WriteLine($"Rectangle Area: {computeArea(5.5, 4.0)}");
// 2. Action delegate for side-effects
Action<string> logMessage = msg => Console.WriteLine($"[LOG {DateTime.UtcNow:HH:mm:ss}] {msg}");
logMessage("Application initialized.");
logMessage("Worker thread running.");
}
}期待される出力:
Rectangle Area: 22 [LOG [time]] Application initialized. [LOG [time]] Worker thread running.
動作のしくみ: ステップ解説
- 6行目: Func は 2 つの double 引数を受け取り double を返します。
- 10行目: Action は string 引数を受け取り void を返します。
重要ポイント
- Func では常に最後のジェネリック型引数が戻り値の型になります。
- Action は最大 16 個の引数を受け取れ、常に void を返します。
よくある間違い: Func と Action を混同すること
Action は値を返しません。ラムダが値を返す場合は Func を使用してください。
❌ 誤り
Action<int, int> add = (a, b) => a + b; // Compile Error: cannot return a value
✅ 正しい例
Func<int, int, int> add = (a, b) => a + b;
関連するC#チュートリアルとコンパイラ
C# メソッド定義の名前付き引数と省略可能な引数
デフォルト値を持つ省略可能引数と順序に依存しない名前付き引数(name: value)を使い、柔軟で明確な C# メソッドを定義します。
C#のクラス、レコード、プロパティ(get; set;)
クラス、自動実装プロパティ({ get; set; })、モダンな C# record を用いてオブジェクトを設計しましょう。
C# の List<T> と LINQ クエリ:Where、Select、Aggregate
動的な List<T> コレクションと強力な LINQ クエリ(Where、Select、Sum)を習得します。
C# オンラインコンパイラ
Compilra IDE で開く