デリゲートとクロージャ
Coddyの「C++開発者のためのC#」コースのレッスン 26/48。
C++のラムダキャプチャリストでは、値キャプチャと参照キャプチャを明示的に区別します。C#のクロージャは、C++のキャプチャリストを使わず、管理されたクロージャモデルを通じて変数をキャプチャします。Func<int,int>はデリゲートのシグネチャを表しますが、C++と同じ有効期間やキャプチャのセマンティクスだと考えないでください。
デリゲートは、パラメーター型と戻り値の型が検査される呼び出し可能な値を表します。Func<int,int>はintを受け取り、intを返します。ラムダは、囲んでいるスコープの変数をキャプチャできます。ブロック形式のラムダでは値を明示的に返す必要があります。式形式のラムダは、その式を返します。
C++の例
#include <algorithm>
#include <array>
#include <cctype>
#include <functional>
#include <iomanip>
#include <iostream>
#include <map>
#include <memory>
#include <optional>
#include <set>
#include <sstream>
#include <stdexcept>
#include <string>
#include <vector>
using namespace std;
int main() {
int offset=4;
function<int(int)> add=[offset](int value){ return value+offset; };
cout << add(3) << "\n";
}
Main内のC#の文
int offset = 4;
Func<int,int> add = value => value + offset;
Console.WriteLine(add(3));これらは、要点に絞った学習用の抜粋です。課題ファイルには実行可能な完全なラッパーが含まれており、上記のスニペットは関連する宣言と文を示しています。
参照出力:
7C#の出力:
7チャレンジ
簡単各値に offset を加えた新しい配列を返してください。offset をキャプチャする Func<int,int> コールバックを定義し、入力を変更せずに適用してください。
ロックされていない C# ファイルを編集してください。表示されているロック済みの Main.cs は、説明されている行を読み込み、Exercise.Solve を呼び出し、入力が変更されていないことを検証して、最後に改行を1つ付けて結果を出力します。宣言されている API を維持してください。2つ目の Main を追加したり、診断出力を表示したりしないでください。
自分で試してみよう
using System;
using System.Linq;
using System.Collections.Generic;
using System.Globalization;
public class Program {
static int I(string text) { return int.Parse(text,CultureInfo.InvariantCulture); }
static int[] Ints(string text) { return text.Length==0 ? new int[0] : text.Split(',').Select(I).ToArray(); }
static string[] Words(string text) { return text.Length==0 ? new string[0] : text.Split(','); }
static string Snapshot(object value) { if (value==null) return "<null>"; if (value is string) return (string)value; var sequence=value as System.Collections.IEnumerable; if (sequence!=null) { var items=new List<string>(); foreach (object item in sequence) items.Add(Snapshot(item)); return string.Join("|",items); } return Convert.ToString(value,CultureInfo.InvariantCulture); }
public static void Main() {
System.Threading.Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
var rows = new List<string>(); string line; while ((line=Console.ReadLine()) != null) rows.Add(line);
string[] input=rows.ToArray();
var a0 = Ints(input[0]); string before0=Snapshot(a0);
var a1 = I(input[1]); string before1=Snapshot(a1);
var result = Exercise.Solve(a0,a1);
if (Snapshot(a0) != before0) throw new Exception("Input mutation");
if (Snapshot(a1) != before1) throw new Exception("Input mutation");
Console.WriteLine("values:" + string.Join(",", result));
}
}
このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。
C++開発者のためのC#のすべてのレッスン
自分で練習してみよう: C#オンラインコンパイラ