为什么是IList的&LT .ForEach(); T&GT;而不是IEnumerable的&LT; T&GT ;? [英] Why is .ForEach() on IList<T> and not on IEnumerable<T>?
问题描述
可能重复:结果
<一href=\"http://stackoverflow.com/questions/101265/why-is-there-not-a-foreach-extension-method-on-the-ienumerable-interface\">Why是不是有IEnumerable接口上一个foreach扩展方法?
我写LINQ-Y code,它.ForEach()是一个很好的成语使用时注意。例如,这里是一片code的,它采用以下输入,并产生这些输出:
I've noticed when writing LINQ-y code that .ForEach() is a nice idiom to use. For example, here is a piece of code that takes the following inputs, and produces these outputs:
{ "One" } => "One"
{ "One", "Two" } => "One, Two"
{ "One", "Two", "Three", "Four" } => "One, Two, Three and Four";
而code:
private string InsertCommasAttempt(IEnumerable<string> words)
{
List<string> wordList = words.ToList();
StringBuilder sb = new StringBuilder();
var wordsAndSeparators = wordList.Select((string word, int pos) =>
{
if (pos == 0) return new { Word = word, Leading = string.Empty };
if (pos == wordList.Count - 1) return new { Word = word, Leading = " and " };
return new { Word = word, Leading = ", " };
});
wordsAndSeparators.ToList().ForEach(v => sb.Append(v.Leading).Append(v.Word));
return sb.ToString();
}
请注意在.ForEach面前的第二个插话.ToList()()到最后一行。
Note the interjected .ToList() before the .ForEach() on the second to last line.
为什么说.ForEach()不能作为对IEnumerable的扩展方法?有了这样的一个例子,它只是似乎不可思议。
Why is it that .ForEach() isn't available as an extension method on IEnumerable? With an example like this, it just seems weird.
由于提前,
戴夫
推荐答案
由于<一个href=\"http://msdn.microsoft.com/en-us/library/bwabdf9z%28VS.80%29.aspx\"><$c$c>ForEach(Action)$c$c>前存在的IEnumerable&LT; T&GT;
存在
既然不与其他扩展方法添加,你可以假设C#的设计师认为这是一个不好的设计和preFER的的foreach
结构。
Since it was not added with the other extension methods, one can assume that the C# designers felt it was a bad design and prefer the foreach
construct.
如果你愿意,你可以创建自己的扩展方法,它不会覆盖一个用于列表&LT; T&GT;
,但它会为任何其他类,它实现工作的IEnumerable&LT; T&GT;
If you want you can create your own extension method, it won't override the one for a List<T>
but it will work for any other class which implements IEnumerable<T>
.
public static class IEnumerableExtensions
{
public static void ForEach<T>(this IEnumerable<T> source, Action<T> action)
{
foreach (T item in source)
action(item);
}
}
这篇关于为什么是IList的&LT .ForEach(); T&GT;而不是IEnumerable的&LT; T&GT ;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!