23
23

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# 備忘録 コールバックについて

Last updated at Posted at 2015-09-01

#コールバック
処理をまとめるときに便利なC#の機能

##何かを実行する

//定義 
System.Action callback = () =>
{
    Debug.Log("もふもふ");
};

//実行 もふもふが表示される
callback();

引数を渡したいときは型パラメータを指定

//定義
System.Action<int> callback = (n) =>
{
    for (int i = 0; i < n; i++)
    {
        Debug.Log("もふもふ");
    }
};

//実行 もふもふが10個表示される
callback(10);

##何かを実行して値を返す
値を返したいときはSystem.Funcを使う

//定義
System.Func<string> callback = () =>
{
    return "もふもふ";
};

//実行 もふもふが表示される
Debug.Log(callback());

引数を渡したいときは型パラメータを複数指定

//定義
System.Func<int,string> callback = (n) =>
{
    if(n%2==0)
    {
        return "偶数";
    }
    else
    {
        return "奇数";
    }
};

//実行 奇数が表示される
Debug.Log(callback(3));
23
23
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
23
23

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?