ITコンサルの日常

ITコンサル会社に勤務する普通のITエンジニアの日常です。

匿名メソッド

プログラミングC# p315

Javaでいう匿名クラスみたいなものか?

using System;

class FunctionPointer
{
        public delegate int twoitem(int a, int b);

        public static int add(int a, int b)
        {
                return a + b;
        }

        public static int sub(int a, int b)
        {
                return a - b;
        }

        static void Main(string[] args)
        {
                // 関数ポインタを定義
                FunctionPointer.twoitem fp;

                fp = FunctionPointer.add;
                Console.WriteLine("result = {0}", fp(5, 3));

                fp = FunctionPointer.sub;
                Console.WriteLine("result = {0}", fp(5, 3));

                fp = delegate(int a, int b)
                {
                        return a * b;
                };
                Console.WriteLine("result = {0}", fp(5, 3));
        }
}

結果はこう。

result = 8
result = 2
result = 15

multメソッドを用意しなくても、いきなりコードブロックで掛け算の処理がかけるってわけです。
ちなみに、さっきのJavaの例を無名クラスで同じように拡張するとこんな感じ。

public class FunctionPointer3
{
        public static void main(String[] args)
        {
                TwoItem ti = new Add();
                System.out.println("result = " + ti.twoitem(5, 3));

                ti = new Sub();
                System.out.println("result = " + ti.twoitem(5, 3));

                ti = new TwoItem()
                {
                        public int twoitem(int a, int b)
                        {
                                return a * b;
                        }
                };
                System.out.println("result = " + ti.twoitem(5, 3));
        }
}

interface TwoItem
{
        public int twoitem(int a, int b);
}

class Add implements TwoItem
{
        public int twoitem(int a, int b)
        {
                return a + b;
        }
}

class Sub implements TwoItem
{
        public int twoitem(int a, int b)
        {
                return a - b;
        }
}

もちろん結果はこう。

result = 8
result = 2
result = 15