| 2019/03/09(Sat) 13:26:31 編集(投稿者)
■No90412 (B.B さん) に返信 > delegate int SimpleFunc(int x); > private int hogeMethod(SimpleFunc func)
.NET Framework 3.5 以降をお使いであれば、Func<> や Action<> が用意されているので、 private int hogeMethod(Func<int, int> func) で済ますこともできますね。
> しかしデリゲードはなかったことにしろという文言をよく見かけます デリゲート(delegate)ですよ; デリゲードでもデリケートでも無く。
> #90396で教えていただいた > isSuccessful = hogeMethod(() => Method3("ほげほげ")); > のようなラムダ式での記述の仕方を教えて欲しいのです
どの部分を書き換えたいのかが読み取れなかったのですが、 > private int method1(int i) > { > i = i * 2; > return i; > } については、「式形式」のメソッドで書けます。
// 要 C# 6.0 以降 private int method1(int i) => i * 2;
hogeMethod(SimpleFunc func) の書き換えなら、 private int hogeMethod(SimpleFunc func) => func(10); private int hogeMethod(SimpleFunc func) => (func ?? delegate { return -1; })(10); private int hogeMethod(SimpleFunc func) => func?.Invoke(10) ?? -1; private int hogeMethod(SimpleFunc func)=> func != null ? func(10) : throw new ArgumentNullException(nameof(func), "引数が空やで"); とか。
button1 での「int result = hogeMethod(method1);」のところで method1 メソッドを定義せずに呼び出したいなら、
// 要 C# 2.0 以降 SimpleFunc proc = new SimpleFunc(delegate(int i) { i *= 2; return i; }); int result = hogeMethod(proc);
// 要 C# 2.0 以降 SimpleFunc proc = delegate(int i) { i *= 2; return i; }; int result = hogeMethod(proc);
// 要 C# 3.0 以降 SimpleFunc proc = (int i) => { i *= 2; return i; }; int result = hogeMethod(proc);
// 要 C# 3.0 以降 SimpleFunc proc = (i) => { i *= 2; return i; }; int result = hogeMethod(proc);
// 要 C# 3.0 以降 SimpleFunc proc = i => { i *= 2; return i; }; int result = hogeMethod(proc);
// 要 C# 2.0 以降 SimpleFunc proc = delegate(int i) { return i * 2; }; int result = hogeMethod(proc);
// 要 C# 2.0 以降 int result = hogeMethod(delegate (int i) { return i * 2; });
// 要 C# 3.0 以降 SimpleFunc proc = i => { return i * 2; }; int result = hogeMethod(proc);
// 要 C# 3.0 以降 int result = hogeMethod(i => { return i * 2; });
// 要 C# 3.0 以降 int result = hogeMethod(i => i * 2); |