LoginSignup
3
3

More than 3 years have passed since last update.

C#のDelegate、Action、Funcの動き

Posted at

概要

DelegateCommandの引数として使用するActionについてよくわかっていなかったため、掘り下げようと思ったが、関係する大元のDelegateがあまりにも多岐にわたりすぎていてとりあえず以下の3つの動きを確認したときの備忘録です。

  • Delgateクラス
  • Acitonデリゲート
  • Funcデリゲート

Delegate

Delegate クラス

デリゲートを表します。デリゲートとは、静的メソッドを参照するデータ構造、またはクラス インスタンスおよびクラスのインスタンス メソッドを参照するデータ構造です。

Delegateクラスの派生としてAction、Funcそれぞれのデリゲートが存在する

まずDelegateクラスがあって、その派生にDelegateから派生したActionデリゲートFuncデリゲートがある。
この名前から想定されるようにActionとFuncの違いはTResultの有無であり、以下のように使い分ける

デリゲート 用途
Action UIの操作(アクション)
Func コールバックなどの関数

以下略以降、T1~T16の最大16個の引数を受け取れるデリゲートが定義されている

- Delegate
    - Action
    - Action<T>, 
    - Action<T1, T2>
    - 以下略
    - Func<TResut>
    - Func<T1, TResult>
    - 以下略

Actionデリゲート

Actionデリゲート

値を返さないメソッドをカプセル化します。

Funcデリゲート

Funcデリゲート

TResult パラメーターで指定された型の値を返すメソッドをカプセル化します。

試したコード

    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("----- Main - Start -----");

            DelegateTarget((string msg) => Console.WriteLine($"{msg} Callback"));

            ActionTarget((string msg) => Console.WriteLine($"{msg} Callback"));

            FuncTarget((string msg) => {
                Console.WriteLine($"{msg} Callback");
                return true;
            });

            Console.WriteLine("----- Main -  End  -----");
        }

        delegate void Callback(string message);
        static void DelegateTarget(Callback callback)
        {
            Console.WriteLine("***** Delegate - Start *****");
            callback("Delegate");
            Console.WriteLine("***** Delegate -  End  *****");
        }

        // 戻り値の設定はできない
        static void ActionTarget(Action<string> action)
        {
            Console.WriteLine("***** Action - Start *****");
            action("Action");
            Console.WriteLine("***** Action -  End  *****");
        }

        // 戻りの型引数は必須
        static void FuncTarget(Func<string, bool> func)
        {
            Console.WriteLine("***** Func - Start *****");
            func("Func");
            Console.WriteLine("***** func -  End  *****");
        }
    }

結果

PS> dotnet run
----- Main - Start -----
***** Delegate - Start *****
Delegate Callback
***** Delegate -  End  *****
***** Action - Start *****
Action Callback
***** Action -  End  *****
***** Func - Start *****
Func Callback
***** func -  End  *****
----- Main -  End  -----
3
3
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
3
3