用 IEnumerable 本来就是为遍历方便,可是现在只有两个选择:
1. foreach,示例代码如下:
IEnumerable<string> strs = new string[] { "a", "b" };foreach (var str in strs)
{
Console.WriteLine(str);
}缺点:代码不简洁,不支持lamda
2. 先ToList,再ForEach,示例代码如下:
IEnumerable<string> strs = new string[] { "a", "b" };
strs.ToList().ForEach(str => Console.WriteLine(str));缺点:ToList有性能代价。
如果 IEnumerable 直接提供 ForEach 操作,就可以这样:
IEnumerable<string> strs = new string[] { "a", "b" };
strs.ForEach(str => Console.WriteLine(str));现在只能通过自己用扩展办法实现:
namespace System.Collections.Generic
{ public static class IEnumerableExtension
{ public static void ForEach<T>(this IEnumerable<T> enumeration, Action<T> action)
{ foreach (var item in enumeration)
{
action(item);
}
}
}
}我的问题是:
微软为什么不考虑到这一点,给IEnumerable增加 ForEach 操作?
为什么 List 有 ForEach 操作,而 IEnumerable 却没有,IEnumerable 更需要它,而且 List 实现了 IEnumerable ?
料青山看我应如是
米琪卡哇伊
翻翻过去那场雪
随时随地看视频慕课网APP