最近、参照型(クラス)の初期化とLinqや拡張メソッドを使った列挙について勉強しています。
これはその成果。
いや~、いろいろな方のブログを拝見し、やっと書けるようになりましたよ~(笑)。
ちなみにQiitaには祝初投稿!
ForEachメソッドは、ArrayにはStaticメソッドとして実装されてるんですね。
Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication8
{
class Program
{
static void Main(string[] args)
{
List<int> intList = new List<int>() { 1, 2, 3 };
List<Employee> employees = new List<Employee>()
{
new Employee {Id = 1, Name = "ジョン" },
new Employee {Id = 2, Name = "ジャック" }
};
Employee[] employees2 = new Employee[]
{
new Employee {Id = 3, Name = "ジョアンナ" },
new Employee {Id = 4, Name = "ジュリア" }
};
foreach (var item in intList)
{
Console.WriteLine($"item={item}");
}
employees.ForEach(o => Console.WriteLine($"Id={o.Id}, Name={o.Name}"));
employees2.ForEach(o => Console.WriteLine($"Id={o.Id}, Name={o.Name}"));
// 拡張メソッドを定義しない場合はこちら
//Array.ForEach(employees2, o => Console.WriteLine($"Id={o.Id}, Name={o.Name}"));
Console.WriteLine("\n\nPush any key!");
Console.ReadKey();
}
}
}
Employee.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication8
{
public class Employee
{
public int Id { set; get; }
public string Name { set; get; }
}
}
ArrayExtension.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication8
{
public static class ArrayExtension
{
public static void ForEach<T>(this T[] employees, Action<T> action)
{
Array.ForEach(employees, action);
}
}
}
#実行結果
item=1
item=2
item=3
Id=1, Name=ジョン
Id=2, Name=ジャック
Id=3, Name=ジョアンナ
Id=4, Name=ジュリア
Push any key!