public static IEnumerable<int> To(this int fromNumber, int toNumber) {
while (fromNumber < toNumber) {
yield return fromNumber;
fromNumber++;
}
}
这允许将 for 循环写成 foreach 循环:
foreach (int x in 0.To(16)) {
Console.WriteLine(Math.Pow(2, x).ToString());
}
我等不及要看其他例子了!享受吧!
最佳答案
这是我最近玩过的一个:
public static IDisposable Tag(this HtmlHelper html, string tagName)
{
if (html == null)
throw new ArgumentNullException("html");
Action<string> a = tag => html.Write(String.Format(tag, tagName));
a("<{0}>");
return new Memento(() => a("</{0}>"));
}
像这样使用:
using (Html.Tag("ul"))
{
this.Model.ForEach(item => using(Html.Tag("li")) Html.Write(item));
using(Html.Tag("li")) Html.Write("new");
}
Memento 是一个方便的类:
public sealed class Memento : IDisposable
{
private bool Disposed { get; set; }
private Action Action { get; set; }
public Memento(Action action)
{
if (action == null)
throw new ArgumentNullException("action");
Action = action;
}
void IDisposable.Dispose()
{
if (Disposed)
throw new ObjectDisposedException("Memento");
Disposed = true;
Action();
}
}
并完成依赖:
public static void Write(this HtmlHelper html, string content)
{
if (html == null)
throw new ArgumentNullException("html");
html.ViewContext.HttpContext.Response.Write(content);
}