1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【読書ノート】《C# in Depth》~5 デリゲート

1
Last updated at Posted at 2017-04-20

デリゲート(delegate: 代表、委譲、委託)とは、メソッドを参照するための型です。 C言語やC++言語の勉強をしたことがある人には、 「デリゲートとは関数ポインターや関数オブジェクトをオブジェクト指向に適するように拡張したもの」 と言った方が分かりやすいかもしれません。

宣言

delegate void StringProcessor(string input);

C#3のデリゲートの書き方がシンプルです

Func<int, int, string> func = (x,y) => (x*y).ToString();
Console.WriteLine(func(5,20));

Funcはジェネリックデリゲート型です。

定義済みデリゲートには大きく2種類あります。
”Action”と”Func”です。
”Action”が戻り値なしのデリゲートで
”Func”が戻り値を持つデリゲートとなります。
引数はそれぞれ4つまで対応しているみたいです。

public void SampleMethod()
        {
            //引数void、戻り値void
            Action act1 = () =>
                {
                    Console.WriteLine("");
                };

            //引数string、戻り値void
            Action<string> act2 = (string value) =>
                {
                    Console.WriteLine(value);
                };

            //引数int,int、戻り値string
            Func<int, int, string> funcAdd = (x, y) =>
                {
                    return (x + y).ToString();
                };

            //呼び出し
            act1();
            act2("");
            string answer = funcAdd(1, 2);
        }

メソッドの中にメソッドを定義することができるじゃん!!
Lua言語みたいな感じですね!

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?