C#扩展方法-距离有多远? [英] C# Extension Methods - How far is too far?

查看:62
本文介绍了C#扩展方法-距离有多远?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Rails对Ruby引入了一些核心扩展,例如3.days.from_now,它返回了,因为您希望将来的日期是三天.使用C#中的扩展方法,我们现在可以执行类似的操作:

Rails introduced some core extensions to Ruby like 3.days.from_now which returns, as you'd expect a date three days in the future. With extension methods in C# we can now do something similar:

static class Extensions
{
    public static TimeSpan Days(this int i)
    {
        return new TimeSpan(i, 0, 0, 0, 0);
    }

    public static DateTime FromNow(this TimeSpan ts)
    {
        return DateTime.Now.Add(ts);
    }
}

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine(
            3.Days().FromNow()
        );
    }
}

或者怎么样:

static class Extensions
{
    public static IEnumerable<int> To(this int from, int to)
    {
        return Enumerable.Range(from, to - from + 1);
    }
}

class Program
{
    static void Main(string[] args)
    {
        foreach (var i in 10.To(20))
        {
            Console.WriteLine(i);
        }
    }
}

这是根本上是错误的,还是有时候是个好主意,例如在Rails之类的框架中?

Is this fundamentally wrong, or are there times when it is a good idea, like in a framework like Rails?

推荐答案

我非常喜欢扩展方法,但我确实感到,在LINQ之外使用扩展方法时,它们会提高可读性,但会牺牲可维护性.

I like extension methods a lot but I do feel that when they are used outside of LINQ that they improve readability at the expense of maintainability.

3.Days().FromNow()为例.这是极好的表达方式,任何人都可以阅读此代码并确切地告诉您它的作用.那真是一件美丽的事.作为编码人员,我们很高兴编写具有自我描述性和表达力的代码,因此几乎不需要注释,并且阅读起来很愉快.在这方面,这段代码至关重要.

Take 3.Days().FromNow() as an example. This is wonderfully expressive and anyone could read this code and tell you exactly what it does. That is a truly beautiful thing. As coders it is our joy to write code that is self-describing and expressive so that it requires almost no comments and is a pleasure to read. This code is paramount in that respect.

但是,作为编码人员,我们还对后代负责,而追随我们的人员将花费大部分时间来尝试理解此代码的工作方式.我们必须小心,不要表现得那么强,以至于调试我们的代码需要在众多扩展方法中跳跃.

However, as coders we are also responsible to posterity, and those who come after us will spend most of their time trying to comprehend how this code works. We must be careful not to be so expressive that debugging our code requires leaping around amongst a myriad of extension methods.

扩展方法掩盖了如何"以更好地表达什么".我猜这使它们成为一把双刃剑,最适合在节制时使用(就像所有事物一样).

Extension methods veil the "how" to better express the "what". I guess that makes them a double edged sword that is best used (like all things) in moderation.

这篇关于C#扩展方法-距离有多远?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆