mugyu
7/29/2014 - 8:24 AM

C# の委譲の例

C# の委譲の例

using System;

// 移譲の型宣言
delegate double MathAction(double num);

class Hoge
{
  // 2の乗算メッソド
  public double Double(double input)
  {
    return input * 2;
  }
}


class DelegateTest
{
  // 2の乗算メッソド
  static double Double(double input)
  {
    return input * 2;
  }

  static void Main()
  {
    // 自クラスの Double メソッドを ma1 に束縛
    MathAction ma1 = Double;
    double multByTwo = ma1(5);
    Console.WriteLine("muitByTow: {0}", multByTwo); // => 10 = 5 * 2

    // 無名メッソドを ma2 に束縛
    MathAction ma2 = delegate(double input)
    {
      return input * input;
    };
    double square = ma2(5);
    Console.WriteLine("Square: {0}", square); // => 25 = 5 * 5

    // ラムダ式を ma3 に束縛
    MathAction ma3 = s => s * s * s;
    double cube = ma3(5);
    Console.WriteLine("Cube: {0}", cube); // => 125 = 5 * 5 * 5

    // 他クラスの Double メッソドを ma4 に束縛
    var hoge = new Hoge();
    MathAction ma4 = hoge.Double;
    double multByTwoFromHoge = ma4(5); // => 10 = 5 * 2
    Console.WriteLine("multByTwoFromHoge: {0}", multByTwoFromHoge);
  }
}