什么是最好或最有趣的使用扩展方法,你见过? [英] What is the best or most interesting use of Extension Methods you've seen?
本文介绍了什么是最好或最有趣的使用扩展方法,你见过?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我开始真的爱扩展方法...我想知道是否有人有她一个真正自爆自己的心意,或者只是在偶然发现聪明。
I'm starting to really love extension methods... I was wondering if anyone her has stumbled upon one that really blew their mind, or just found clever.
今天我写了一个例子:
由于其他用户的评论编辑:
public static IEnumerable<int> To(this int fromNumber, int toNumber) {
while (fromNumber < toNumber) {
yield return fromNumber;
fromNumber++;
}
}
这使得for循环可以写成一个foreach循环:
This allows a for loop to be written as a foreach loop:
foreach (int x in 0.To(16)) {
Console.WriteLine(Math.Pow(2, x).ToString());
}
我等不及看其他的例子!尽情享受吧!
I can't wait to see other examples! Enjoy!
推荐答案
这是一个已经得到一些游戏从我最近:
This is one that's been getting some play from me lately:
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 is a handy class:
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);
}
这篇关于什么是最好或最有趣的使用扩展方法,你见过?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文