困った時の自分用メモ

読んだ本を考察してメモったり、自分でいじった物の感想をメモったりする場。週1更新を目指します。

C#の話~戻り値を返すコールバック宣言方法~

今まで、コールバックは戻り値を返す事が無かった、もしくは、引数にコールバック関数を渡して、パラメータを渡してもらっていたのだが、
戻り値普通に受け取る方法無いのかなと思って調べたら、あったのでメモ。

docs.microsoft.com

Func<引数1, 引数n, 戻り値>
で宣言すればよい。

using System;
using UnityEngine;

public class FuncCallbackTest : MonoBehaviour
{
    private Func<string, int> ReturnIntCallback = null;
    // Start is called before the first frame update
    void Start()
    {
        Test();
    }

    private void Test()
    {
        ReturnIntCallback = ReturnIntFunction;
        int res = ReturnIntCallback("10");
        Debug.Log(res);// 10
    }

    private int ReturnIntFunction(string arg)
    {
        int res = int.Parse(arg);
        return res;
    }
}