Delegate を渡す

C# で Delegate を引数として渡します。

前田稔(Maeda Minoru)の超初心者のプログラム入門

プログラムの説明

  1. delegate をパラメータとしてメソッドに渡すことも出来ます。
    二個のメソッドを定義して、パラメータとして渡してみましょう。
  2. デリゲートから呼び出される二個のメソッドを定義します。
        class Class2
        {
            public int methodMult( int x, int y )
            {
                return x*y;
            }
            public int methodPlus( int x, int y )
            {
                return x+y;
            }
        }
        
  3. デリゲートをパラメータとして受け取るメソッドです。
    渡されたデリゲートを通じて実際に処理を行うメソッドを呼び出します。
        public static void callm( int x, int y, TestDelegate callMethod )
        {
            int result = callMethod( x, y );
            Console.WriteLine( result );
        }
        
  4. class2 に Class2 を生成して、デリゲートをパラメータとして渡します。
    渡すメソッドは、型と引数が一致していなければなりません。
        Class2 class2 = new Class2();
        callm( 3, 4, new TestDelegate( class2.methodMult ) );
        callm( 3, 4, new TestDelegate( class2.methodPlus ) );
        
  5. プログラムの全ソースコードです。
    Delegate の基礎は Delegate の基礎 を参照して下さい。
    /****************************************/
    /*★ Delegate を引数で渡す    前田 稔 ★*/
    /****************************************/
    using System;
    
    namespace ConsoleApp
    {
        delegate int TestDelegate( int x, int y );
        class Class2
        {
            public int methodMult( int x, int y )
            {
                return x*y;
            }
            public int methodPlus( int x, int y )
            {
                return x+y;
            }
        }
    
        class Class1
        {
            public static void callm( int x, int y, TestDelegate callMethod )
            {
                int result = callMethod( x, y );
                Console.WriteLine( result );
            }
            static void Main(string[] args)
            {
                Class2 class2 = new Class2();
                callm( 3, 4, new TestDelegate( class2.methodMult ) );
                callm( 3, 4, new TestDelegate( class2.methodPlus ) );
                Console.ReadLine();
            }
        }
    }
    

超初心者のプログラム入門(C# Frame Work)