3
3

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.

ForEach()メソッドをシンプルに書けるようにする

Posted at

ジェネリック版コレクションに備わっているForEach()メソッドですが、
下記ソースコードの a ではなく b のような書き方したい!

program.cs
using System;
using Rohinomiya;

namespace SampleForEach
{
	class Program
	{
		public static void Main(string[] args)
		{
			var dirs = new string[]{"aa","bb","cc"};
			
			Array.ForEach<string>(dirs, s => Console.WriteLine(s) );	// a
			dirs.ForEach(s => Console.WriteLine(s));					// b:こういう書き方したい

		}
	}
}

というわけで、Arrayクラスを拡張して、ForEach()メソッドを書いてみました。

ClassArrayExtension.cs
using System;

namespace Rohinomiya
{
	/// <summary>
	/// Arrayクラスを拡張する
	/// </summary>
	public static class ArrayExtension
	{
		/// <summary>
		/// ForEachメソッド
		/// </summary>
		/// <param name="array">Arrayクラス</param>
		/// <param name="action">実行させたいActionデリゲート</param>
		public static void ForEach<T>(this T[] array, Action<T> action)
		{
			Array.ForEach<T>(array, obj => action(obj));
		}
	}
}

3
3
2

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?