【C#】Delegate / Event ~ Func デリゲート ~

■ はじめに

https://dk521123.hatenablog.com/entry/2010/12/12/164101
https://dk521123.hatenablog.com/entry/2010/12/25/221009
https://dk521123.hatenablog.com/entry/2010/10/22/101350

の続き。

 ■ Func デリゲート

 Func<T, TResult>の意味

 * T型の引数を1つ、戻り値TResultのメソッドをとるデリゲート

※ Action デリゲートとの違い

 * Funcデリゲート   : 戻り値あり
 * Actionデリゲート : 戻り値なし

 種類

Func<TResult>
Func<T, TResult>
Func<T1, T2,... TResult>

 構文

Func<(【引数の型】,)【戻り値の型】> 【メソッド名】 = (【引数】) => 【式】;

 ■ サンプル

 例1

private void button1_Click(object sender, EventArgs e)
{
    Func<int> f1 = () => 1;
    this.label1.Text = f1().ToString(); // 出力結果:1

    Func<int, int> f2 = (x) => x * 2;
    this.label2.Text = f2(2).ToString(); // 出力結果:4

    Func<int, int, int> f3 = (x, y) => x * y;
    this.label3.Text = f3(3, 4).ToString(); // 出力結果:12
}

 例2

SampleFunc.cs (今回の注目ポイント)

using System;

namespace WindowsFormsApplication1
{
    public class SampleFunc
    {
        private CommonLibrary commonLibrary;

        public SampleFunc(CommonLibrary commonLibrary)
        {
            this.commonLibrary = commonLibrary;
        }

        public T doIt<T>(Func<CommonLibrary, T> action)
        {
            return action(this.commonLibrary);
        }
    }
}

CommonLibrary.cs (使用する関数本体)

namespace WindowsFormsApplication1
{
    public class CommonLibrary
    {
        public int Plus(int a, int b)
        {
            return a + b;
        }

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

Form1.cs (使用者)

using System;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        private SampleFunc sampleFunc = new SampleFunc(new CommonLibrary());
        
        public Form1()
        {
            InitializeComponent();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            this.label1.Text = 
                this.sampleFunc.doIt(x => x.Plus(1, 2)).ToString();
        }

        private void button3_Click(object sender, EventArgs e)
        {
            this.label1.Text =
                this.sampleFunc.doIt(x => x.Minus(10, 2)).ToString();
        }
    }
}

 参考文献

http://gushwell.ldblog.jp/archives/51216239.html#
http://csharp30matome.seesaa.net/article/130537491.html
http://ufcpp.net/study/csharp/sp2_anonymousmethod.html
http://www.atmarkit.co.jp/fdotnet/csharp30/csharp30_02/csharp30_02_02.html

 関連記事

Delegate / Event ~ 入門編 / Delegate
https://dk521123.hatenablog.com/entry/2010/12/12/164101
Delegate / Event ~ 入門編 / Event ~
https://dk521123.hatenablog.com/entry/2010/12/25/221009