Are extension methods an object-oriented feature of C#?

前端 未结 6 1301
迷失自我
迷失自我 2020-12-19 16:48

Do extension methods follow the object-oriented paradigm in C#?

Is it a good practice to use extension methods?

In the software development lifecycle how s

6条回答
  •  有刺的猬
    2020-12-19 17:32

    Eric Lippert has blogged about this and I suspect I can't do much better than to quote him:

    So, yes, the oft-heard criticism that "extension methods are not object-oriented" is entirely correct, but also rather irrelevant. Extension methods certainly are not object-oriented. They put the code that manipulates the data far away from the code that declares the data, they cannot break encapsulation and talk to the private state of the objects they appear to be methods on, they do not play well with inheritance, and so on. They're procedural programming in a convenient object-oriented dress.

    They're also incredibly convenient and make LINQ possible, which is why we added them. The fact that they do not conform to some philosophical ideal of what makes an object-oriented language was not really much of a factor in that decision.

    I would add, however, that they're useful beyond just LINQ - for the same reason that they're useful in LINQ. It's really nice to be able to express algorithms which work on arbitrary implementations of a particular interface (such as IEnumerable in LINQ to Obhects). Such algorithms typically don't have any context beyond the interfaces you're working on, so they're often naturally static.

    If you accept that you've got some static utility method, which syntax would you rather use?

    // Traditional
    CollectionUtils.Sort(collection);
    
    // Extension methods
    collection.Sort();
    

    The latter is simply more readable in my opinion. It concisely expresses what you want to do. It doesn't make it clear how you want to do it, but that's less important for most of the time - and more important when you're debugging that particular line, of course.

提交回复
热议问题