Каждый раз, когда мне нужно что-то сделать, N раз внутри алгоритма, использующего C#, я пишу этот код
for (int i = 0; i < N; i++)
{
...
}
Изучая Ruby, я узнал о методе раз (), который можно использовать с такой же семантикой, как эта.
N.times do
...
end
Фрагмент кода в C# выглядит более сложным, и нам следует объявить бесполезную переменную я.
Я попытался написать метод расширения, который возвращает IEnumerable, но меня не устраивает результат, потому что я снова должен объявить переменную цикла я.
public static class IntExtender
{
public static IEnumerable Times(this int times)
{
for (int i = 0; i < times; i++)
yield return true;
}
}
...
foreach (var i in 5.Times())
{
...
}
Возможно ли использование некоторых новых функций языка C# 3.0, чтобы сделать цикл N более элегантным?





Это действительно возможно с C# 3.0:
public interface ILoopIterator
{
void Do(Action action);
void Do(Action<int> action);
}
private class LoopIterator : ILoopIterator
{
private readonly int _start, _end;
public LoopIterator(int count)
{
_start = 0;
_end = count - 1;
}
public LoopIterator(int start, int end)
{
_start = start;
_end = end;
}
public void Do(Action action)
{
for (int i = _start; i <= _end; i++)
{
action();
}
}
public void Do(Action<int> action)
{
for (int i = _start; i <= _end; i++)
{
action(i);
}
}
}
public static ILoopIterator Times(this int count)
{
return new LoopIterator(count);
}
Использование:
int sum = 0;
5.Times().Do( i =>
sum += i
);
Бесстыдно украдено из http://grabbagoft.blogspot.com/2007/10/ruby-style-loops-in-c-30.html
Если вы используете .NET 3.5, вы можете использовать метод расширения Each, предложенный в этой статье, и использовать его, чтобы избежать классического цикла.
public static class IEnumerableExtensions
{
public static void Each<T>(
this IEnumerable<T> source,
Action<T> action)
{
foreach(T item in source)
{
action(item);
}
}
}
This particular extension method spot welds an Each method on anything that implements IEnumerable. You know this because the first parameter to this method defines what this will be inside the method body. Action is a pre-defined class that basically stands in for a function (delegate) returning no value. Inside the method, is where the elements are extracted from the list. What this method enables is for me to cleanly apply a function in one line of code.
(http://www.codeproject.com/KB/linq/linq-to-life.aspx)
Надеюсь это поможет.
Немного более короткая версия ответ cvk:
public static class Extensions
{
public static void Times(this int count, Action action)
{
for (int i=0; i < count; i++)
{
action();
}
}
public static void Times(this int count, Action<int> action)
{
for (int i=0; i < count; i++)
{
action(i);
}
}
}
Использовать:
5.Times(() => Console.WriteLine("Hi"));
5.Times(i => Console.WriteLine("Index: {0}", i));
Я написал собственное расширение, которое добавляет Times к Integer (плюс еще кое-что). Вы можете получить код здесь: https://github.com/Razorclaw/Ext.NET
Код очень похож на ответ Джона Скита:
public static class IntegerExtension
{
public static void Times(this int n, Action<int> action)
{
if (action == null) throw new ArgumentNullException("action");
for (int i = 0; i < n; ++i)
{
action(i);
}
}
}