C#のデリゲート

デリゲートはメソッドの型を定義するものです。
どのようなパラメータを持ち、どのような戻り値なのかというメソッドの構造を決めておく仕組みです。

デリゲートは型なので、この型の変数を作る事ができます。
変数にはデリゲートで定義したのと同じ構造のメソッド(メソッドの参照)を代入する事ができます。

デリゲートを使えば、条件によって呼び出すメソッドを変えるといったことが容易に行えるようになります。



デリゲートの定義

デリゲートはキーワード(予約語) delegate を使って宣言します。
  1. delegate 戻り値の型 デリゲート名(パラメータ);
delegate が付いている以外はメソッド定義の1行目と同じです。
デリゲートは型を定義するものなので必要なのはこれだけです。



デリゲートの使い方

条件によって呼び出すメソッドを変える

以下の例では、条件によって呼び出すメソッドを変えるています。
  1. public delegate void TestDelegate(int num1, int num2);
  2.  
  3. public class Program
  4. {
  5. public static void TestMethod1(int num1, int num2)
  6. {
  7. int answer = num1 + num2;
  8. Console.Write("足し算の結果は{0}", answer);
  9. }
  10.  
  11. public static void TestMethod2(int num1, int num2)
  12. {
  13. int answer = num1 - num2;
  14. Console.Write("引き算の結果は{0}", answer);
  15. }
  16.  
  17.  
  18. public static void Main()
  19. {
  20. int num1 = 100;
  21. int num2 = 500;
  22. TestDelegate method; //デリゲート型の変数を作成
  23. if (num1 < num2)
  24. {
  25. method = TestMethod1; //メソッドTestMethod1の参照を代入
  26. }
  27. else
  28. {
  29. method = TestMethod2; //メソッドTestMethod2の参照を代入
  30. }
  31. method(num1, num2); //メソッドを呼び出し(TestMethod1が実行される)
  32. }
  33. }


メソッドのパラメータに利用する

デリゲートはメソッドのパラメータとしても利用する事ができます。
  1. public delegate int TestDelegate(int num);
  2.  
  3. public class Program
  4. {
  5. public static int TestMethod(int num)
  6. {
  7. return num * 2;
  8. }
  9.  
  10. public static void EditArray(int[] list, TestDelegate method) // パラメータがデリゲートが使われている
  11. {
  12. for (int i = 0; i < list.Length; ++i)
  13. {
  14. list[i] = method(list[i]); // 配列の全要素に対して処理を行っている
  15. }
  16. }
  17.  
  18.  
  19. public static void Main()
  20. {
  21. int[] list;
  22. list = new int[10];
  23. for (int i = 0; i < list.Length; ++i)
  24. {
  25. list[i] = i;
  26. }
  27. EditArray(list, TestMethod); // パラメータにメソッドを渡している
  28. }
  29. }


複数のメソッドを代入する

デリゲートには += 演算子を使う事で複数のメソッドを代入する事ができます。
複数のメソッドが代入された場合、その全てが実行されます。
また、 -= 演算子を使うと代入したメソッドの参照を削除する事もできます。
  1. public delegate void TestDelegate(int num1, int num2);
  2.  
  3. public class Program
  4. {
  5. public static void TestMethod1(int num1, int num2)
  6. {
  7. int answer = num1 + num2;
  8. Console.Write("足し算の結果は{0}", answer);
  9. }
  10.  
  11. public static void TestMethod2(int num1, int num2)
  12. {
  13. int answer = num1 - num2;
  14. Console.Write("引き算の結果は{0}", answer);
  15. }
  16.  
  17.  
  18. public static void Main()
  19. {
  20. int num1 = 100;
  21. int num2 = 500;
  22. TestDelegate method; //デリゲート型の変数を作成
  23. method = TestMethod1; //メソッドTestMethod1の参照を代入
  24. method += TestMethod2; //メソッドTestMethod2の参照を追加で代入
  25. method(num1, num2); //メソッドを呼び出し(TestMethod1とTestMethod2の両方が実行される)
  26.  
  27.  
  28. method -= TestMethod1; //メソッドTestMethod1の参照を削除
  29. method(num1, num2); //メソッドを呼び出し(TestMethod2だけが実行される)
  30. }
  31. }



コメント