c# - 您见过的最好或最有趣的扩展方法用法是什么?

标签 c# .net extension-methods syntactic-sugar

<分区>

我开始真正喜欢上扩展方法……我想知道她是否有任何人偶然发现了一个真正让他们大吃一惊的方法,或者只是发现了一个聪明的方法。

我今天写的一个例子:

根据其他用户的评论进行编辑:

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);
}

关于c# - 您见过的最好或最有趣的扩展方法用法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/954198/

相关文章:

generics - 如何为泛型类型编写扩展方法,其中一个类型变量必须是字符串?

c# - Windows Phone 二维码阅读器

C#:通过 TextReader 的 ReadLine() 解析带有一个定界符的字符串的有效方法是什么?

c# - 从 View 模型更新记录的正确方法是什么?

c# - 在 DataPager 中获取事件号码页

.net - Visual Studio 2010 : Properties. 将项目重定向到 .NET Framework 3.5 后设置损坏

c# - 为什么使用 Google Cloud Firestore 1.0.0-beta05 C# SetAsync 时会出现 Grpc.Core.RpcException StatusCode=Unavailable, Detail ="Connect Failed"?

javascript - CSV 文件作为单个字符串返回

c# - 使用动态类型调用泛型扩展方法

c# - IQueryable<T> 上的通用扩展方法