インスタンスメソッドを変数に格納する
用途としては、いくつかのメソッドのうちからランダムなメソッドを呼び出したいときに、 一時的に配列に格納したいとき等に使います。
using System; class Test { public void Foo() { Console.WriteLine("Foo"); } public void Bar(int n) { Console.WriteLine("Bar {0}", n); } public int Baz(int n) { return n + 1; } } class Program { static void Main() { var t = new Test(); Action f = t.Foo; f(); // Foo Action<int> g = t.Bar; g(20); // Bar 20 Func<int, int> h = t.Baz; int ret = h(10); Console.WriteLine(ret); // 11 } }
インスタンスメソッドの型に応じて、Action
, Action<int>
, Func<int, int>
と変数の型が異なります。
Action は戻り値なし、Func は戻り値がある場合の型です。
実行結果です。
Foo Bar 20 11
インスタンスメソッドを配列に格納してランダムに呼び出す
じゃんけんの手をランダムに選ぶサンプルです。 インスタンスメソッドを配列に格納して、ランダムな要素を選択しています。
using System; class Hand { public void Guu() { Console.WriteLine("グー"); } public void Cho() { Console.WriteLine("チョキ"); } public void Paa() { Console.WriteLine("パー"); } } class Program { static void Main() { var hand = new Hand(); Action[] actions = { hand.Guu, hand.Cho, hand.Paa }; var rand = new Random(); for (int i = 0; i < 5; i++) { int p = rand.Next(actions.Length); actions[p](); } } }
実行結果です。
グー チョキ チョキ グー パー