2016年12月18日日曜日

デリゲートについて C#

C#のデリゲートのActionとFuncについて、デリゲートとは簡単に言えば委譲らしいです。
委譲とは? A.他にゆだね、ゆずること。。。
自分もあまりよくわかってないのですが、関数が変数のように扱えるようなものだと思っています。
関数を変数で扱える、つまり関数が入った変数を実行すると入れた関数が実行されるということです。

ActionとFuncの違いについて。
Actionは返り値がない
Funcは返り値がある
だけの違いですかね?

使用する場合は
using System;
が必要です


以下テストコード

using UnityEngine;
using System;

public class DelegateTest : MonoBehaviour
{
    // デリゲート
    Action testActionDelegate;

    // デリゲート(返り値)
    Func<int> testFuncDelegate;

    // デリゲート(引数あり)
    Action<string> testStrActionDelegate;

    // Use this for initialization
    void Start ()
    {
        // 実行したい関数を入れる
        testActionDelegate = testAction;
        testFuncDelegate = testFunc;
        testStrActionDelegate = testStrAction;


        // Nullチェック
        if (testActionDelegate != null)
        {
            // デリゲートを実行する
            testActionDelegate();
        }

        // Nullチェック
        if (testFuncDelegate != null)
        {
            // デリゲートを実行する
            testFuncDelegate();
        }

        // Nullチェック
        if (testStrActionDelegate != null)
        {
            // デリゲートを実行する
            testStrActionDelegate("testStrAction");
        }

    }

    public void testAction ()
    {
        Debug.Log("testAction");
    }

    public int testFunc ()
    {
        Debug.Log("testFunc");
        return 0;
    }

    public void testStrAction (string str)
    {
        Debug.Log(str);
    }
}
  実行すると以下のログが出れば成功です。(Unityで実行してます)

0 件のコメント :

コメントを投稿

【早い者勝ち!】 あなたのお名前、残ってる?

シャドウバースにPC版が誕生