LoginSignup
5
8

More than 5 years have passed since last update.

指定回数処理を繰り返すメソッド(拡張メソッド)

Posted at

以前の記事に関連して、Ruby の int.Times() メソッドみたいなのを書いてみました。

int クラスに対して、n 回繰り返す拡張メソッドを追加するには、以下のように適当な名前の静的クラスに、拡張メソッドを記述します。
1つ目の引数に、this キーワードを付けると、あたかもその型に対するメソッドのように使えます。

ソースコード

ClassIntExtensions.cs
namespace Rohinomiya
{
    /// <summary>
    /// intクラスを拡張する
    /// </summary>
    public static class IntExtensions
    {
        /// <summary>
        /// [count] 回 処理を繰り返す
        /// 
        /// 使用例: 3.Times( i => Console.WriteLine(i.ToString()));
        /// </summary>
        /// <param name="count">繰り返す回数</param>
        /// <param name="action">実行させたいActionデリゲート</param>
        public static void Times(this int count, Action<int> action)
        {
            for (int i = 1; i <= count; i++) 
                action(i);
        }
    }
}

使用例

3.Times( i => Console.WriteLine(i.ToString()));

実行結果

1
2
3
5
8
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
5
8